Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/423.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 检查字符串中是否存在子字符串_Javascript_Typescript - Fatal编程技术网

Javascript 检查字符串中是否存在子字符串

Javascript 检查字符串中是否存在子字符串,javascript,typescript,Javascript,Typescript,我想检查子字符串是否包含在字符串中,但是子字符串包含一个数字,这个数字可以更改。我使用了RegExp,但它不起作用 let url = "http://localhost:8080/api/issue/board/537/sprint"; url.includes('/issue/board/537/sprint'); // true 值537可以更改 var reg = new RegExp('^[0-9]+$'); url.includes('/issue/board/' + reg

我想检查子字符串是否包含在字符串中,但是子字符串包含一个数字,这个数字可以更改。我使用了RegExp,但它不起作用

let url = "http://localhost:8080/api/issue/board/537/sprint";

url.includes('/issue/board/537/sprint'); // true
值537可以更改

var reg = new RegExp('^[0-9]+$');

url.includes('/issue/board/' + reg  +'/sprint'); // false

最简单的方法就是使用indexOf。像这样

let url = "http://localhost:8080/api/issue/board/537/sprint",
    match = '/issue/board/537/sprint';

if (url.indexOf(match) !== -1) {
  // true
} else {
  // false 
}
您正在检查的字符串中不包含的字符串的索引将始终为-1

var reg=new RegExp('/issue/board/[0-9]+/sprint')

这不是使用正则表达式的方式

创建表达式:

const reg = new RegExp('/issue/board/[0-9]+/sprint');
并根据您的url进行测试:

const url = "http://localhost:8080/api/issue/board/537/sprint";
const matches = url.test(reg); // true
const condition=new RegExp('\/issue\/board\/[0-9]+\/sprint')。测试('http://localhost:8080/api/issue/board/537/sprint'); // 真的
const reg=new RegExp('/issue/board/[0-9]+/sprint');
常量url=”http://localhost:8080/api/issue/board/537/sprint";
const matches=url.match(reg);

log(matches?true:false)
您需要使用一种正则表达式方法,如
test
match
来“使用正则表达式”。目前,您只是将正则表达式连接到一个字符串中,并使用常规子字符串搜索。
const regex = new RegExp('\/board\/(.*?)\/sprint');

const url = 'http://localhost:8080/api/issue/board/537/sprint';
const test = regex.test(url);
const matches = regex.exec(url);

console.log(test); // true
console.log(matches[1]); //537