简体   繁体   中英

Find substring position into string with Javascript

I have the following strings

"www.mywebsite.com/alex/bob/a-111/..."
"www.mywebsite.com/alex/bob/a-222/..."
"www.mywebsite.com/alex/bob/a-333/...".

I need to find the a-xxx in each one of them and use it as a different string. Is there a way to do this? I tried by using indexOf() but it only works with one character. Any other ideas?

You can use RegExp

 var string = "www.mywebsite.com/alex/bob/a-111/..."; var result = string.match(/(a-\\d+)/); console.log(result[0]); 

or match all values

 var strings = "www.mywebsite.com/alex/bob/a-111/..." + "www.mywebsite.com/alex/bob/a-222/..." + "www.mywebsite.com/alex/bob/a-333/..."; var result = strings.match(/a-\\d+/g) console.log(result.join(', ')); 

Use the following RegEx in conjunction with JS's search() API

/(a)\-\w+/g

Reference for search(): http://www.w3schools.com/js/js_regexp.asp

var reg=/a-\d{3}/;
text.match(reg);

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