简体   繁体   中英

Using wildcard in string in Javascript

How can one represent a range of numbers in a string in javascript?

So for example,

var Ages = "This member is x years old";

where x can be any nunber at all.

I want to be able to search for such string in an array of strings.

Javascript is really good for concatenations.

var x = // the age value you are searching for;

var ages = "The member is " + x + " years old";

You can then just wrap this in a loop.

With a regular expression, match and capture \d+ (one or more digits) in place of the x :

 const pattern = /This member is (\d+) years old/; const input = prompt('Input?', 'This member is 99 years old'); const match = pattern.exec(input); if (match) { console.log(match[1]); } else { console.log('Format not recognized'); }

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