Reputation: 487
I want to add $ sign when any number found in my string.
ie.
"This 123 and if we add 2 in 123 than it becomes 125." //-this is string not a question.
out is like.
This $123 and if we add $2 in $123 than it becomes $125.
Upvotes: 0
Views: 40
Reputation: 18987
use regex
to add the $
before the numbers
alert("This 123 and if we add 2 in 123 than it becomes 125".replace(/(\s)(?![a-z A-Z]+)/g, " $"));
Upvotes: 0
Reputation: 2412
Try this
var str = "This 123 and if we add 2 in 123 than it becomes";
var t = str.split(" ");
var c = 0;
var e = 0;
var d = "";
for (var i = 0; i < t.length; i++) {
if (parseInt(t[i])) {
d = d + " " + "$" + t[i]
c += parseInt(t[i]);
e = parseInt(t[i]);
} else {
d = d + " " + t[i]
}
}
alert(d + " $" + (c - e))
Upvotes: 0
Reputation: 1239
var string = "This 123 and if we add 2 in 123 than it becomes 125.".replace(/([0-9]{1,9})/g,
function(str){
return "$"+str;
});
document.writeln(string);
https://jsfiddle.net/d44yawb3/
Upvotes: 0
Reputation: 67207
You can do it like by using regex
and replace
's with its callBack
signature,
var str = "This 123 and if we add 2 in 123 than it becomes 125";
str = str.replace(/\d+/g, function(v){
return "$" + v;
});
console.log(str); //This $123 and if we add $2 in $123 than it becomes $125
Upvotes: 3