简体   繁体   中英

check if substring exist in string

I want to check if a sub string is included in a string, but the sub string contains a number, this number can change. I used RegExp but it's not working

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

url.includes('/issue/board/537/sprint'); // true

the value 537 can change

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

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

That's not how you use Regex.

Create an expression:

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

And test it against your url:

const url = "http://localhost:8080/api/issue/board/537/sprint";
const matches = url.test(reg); // true
var reg = new RegExp('/issue/board/[0-9]+/sprint')
const condition = new RegExp('\/issue\/board\/[0-9]+\/sprint').test('http://localhost:8080/api/issue/board/537/sprint'); // true

 const reg = new RegExp('/issue/board/[0-9]+/sprint'); const url = "http://localhost:8080/api/issue/board/537/sprint"; const matches = url.match(reg); console.log(matches ? true: false)

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

Easiest way is just to use indexOf. Like so

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

if (url.indexOf(match) !== -1) {
  // true
} else {
  // false 
}

The indexOf a string that isn't contained in the string you're checking will always be -1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM