Pravin Tukadiya
Pravin Tukadiya

Reputation: 487

How to Add $ in digit using Jquery

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

Answers (4)

Rajshekar Reddy
Rajshekar Reddy

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

Krupesh Kotecha
Krupesh Kotecha

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

mondjunge
mondjunge

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

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

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

DEMO

Upvotes: 3

Related Questions