Sathya Sathya - 4 months ago 8
CSS Question

Extract words that starts with a certain character from a string in Javascript

I have a string as shown below

var str = "This product price is £15.00 and old price is £19.00";


I need to get the word that start with "£";
Result should be "£15.00" "£19.00"
How do I do it in Javascript?

Answer

Use String#match method

var str = "This product price is £15.00 and old price is £19.00";

// if `£` follows non-digit also then use
console.log(str.match(/£\S+/g));
// if `£` follows only number with fraction
console.log(str.match(/£(\d+(\.\d+)?)/g));

Comments