Reputation: 10818
I have a string that contain numbers separated by the dots e.g: "2.3.19" or "56.3.10", etc
Sometime string might contain text say "33.4.5.6-any-text-here".
How would you strip the non-numeric text from the string leaving just numbers separated by the dots?
I've tried this solution:
Number(("33.4.5.6any-text-here").match(/\d+$/));
but that returns 0
Upvotes: 0
Views: 86
Reputation: 299
let str = "33.4.5.6-any-text-here"
let finStr = str.replace(/[^\d.]/g, ''); // .replace(/[^\d|^\.]/g, '')
console.log(finStr); // 33.4.5.6
Upvotes: 0
Reputation: 7357
This should work:
"33.4.5.6-any-text-here".match(/[0-9.]*/)[0]
[0-9.]
matches any number 0-9, and the dot (.).*
matches 0 or more of the previous pattern (digit or dot).match
always returns an array in this case (when the 'g' flag is not used in the regex) we can safely return the first item of the array ([0]
). It always returns an array in this case because we said "zero or more". Thus, if zero, it matches nothing and returns an empty string if nothing is found.Upvotes: 4