In JavaScript, what would be the regular expression for a number followed by a word? I need to catch the number AND the word and replace them both after some calculation.
Here are the conditions in a form of example:
123 dollars => Catch the '123' and the 'dollars'.
foo bar 0.2 dollars => 0.2 and dollars
foo bar.5 dollar => 5 and dollar (notice the dot before 5)
foo bar.5.6 dollar => 5.6 and dollar
foo bar.5.6.7 dollar => skip (could be only 0 or 1 dot)
foo bar5 dollar => skip
foo bar 5dollar => 5 and dollar
5dollar => 5 and dollar
foo bar5dollar => skip
- Of course 123.555, 0.365, 5454.1 are numbers too.
-
For making things simpler the word is a specific one (e.g
dollar|euro|yen). -
OK.. Thank you all… Here is the basic function I made so far:
var text = “foo bar 15 dollars. bla bla..”;
var currencies = {
dollars: 0.795
};document.write(text.replace(/\b((?:\d+.)?\d+) *([a-zA-Z]+)/, function(a,b,c){
return currencies[c] ? b * currencies[c] + ‘ euros’ : a;
}
));
Try this:
That will also match stuff like
.5 tests. If you don’t want that, use this:And to avoid matching “5.5.5 dollars”: