简体   繁体   中英

Regular Expression to find a value in a string

I've got a bunch of strings that look like this:

  • This is string 1 [id:10]
  • This is string 2 [id:4]
  • This is string 3 [id:77]

Using javascript, how can I get an array of 10,4,77? These will be values of input fields all with the class form-text so I have the option of iterating of them.

Thanks, Howie

Lets say you have the given strings in array. Then using Array.map you can retrieve the id's

var a = ["This is string 1 [id:10]", "This is string 2 [id:4]", "This is string 3 [id:77]"];

var result = a.map(function (item) {
    return /.*?\[id:([\d]{1,})\]/g.exec(item)[1];
});

console.log(result);
\d+(?=\])

Try this.See demo .

https://regex101.com/r/vN3sH3/18

You could do something like this:

var test = "[id:10]";
var result = test.split(":")[1].split("]")[0];
//result should have 10

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