How to get a word after specific word?
For example: I have string like this :
string = "Price:$20 is very cheap"
I want get result: $20
How can I do that with Javascript?
You can use regex:
var matches = /Price:(.*?) /g.exec("Price:$20 is very cheap");
if(matches.length > 1) {
var price = matches[1];
}
else {
// Not found
}
Note this will match any sequence of characters after the word Price: . If there is whitespace after the word price, it will break. If there is no space after $20, it will break. You need to make the rules more complex depending on your input source.
用:分隔字符串,然后用空格分隔。
string.split(":")[1].split(" ")[0]
Various solutions without regular expressions :
var s = 'Price:$20 is very cheap';
var s1 = s.slice(6, s.indexOf(' '));
var s2 = s.slice(s.indexOf(':') + 1, s.indexOf(' '));
var s3 = s.slice(s.indexOf('$'), s.indexOf(' '));
// s1 === s2 === s3 === "$20"
var str = 'Price:$20 is very cheap';
var price = str.split(' ')[0].split(':')[1]; // $20
var matches = /Price:(\$\d+)/.exec(string)
matches[1];//"$20"
You can use string.split(":")[1].split(" ")[0]
or else you can use combination of str.substring();
& str.indexOf();
.Fiddle example:
使用正则表达式是一种更好的方法,因为字符串方法不能在所有情况下都返回正确的答案。
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.