Javascript: Get Word After Specific Word?

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?

0

7 Answers

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.

3

Split the string by : and then with space.

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:

Using Regular Expression is a better way, as string methods cannot return correct answers on all cases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest