Replacing a number in a string with jquery

I have a line in which there is a number that I would like to replace with another number.

t

<a href="" id="my_link">blah blah 32 blah blah</a> 

I know that in this line there will be only 1 number.

I can go this far:

 var my_string = $('a#my_link').text(); 

But basically I don’t know how to search my_string for a digit and replace that number with something else.

Is this possible with jQuery?

Thanks for any ideas.

+7
jquery
source share
5 answers

Many jQuery methods, such as .text() , can take a function that returns a value to be inserted.

Try: http://jsfiddle.net/6mBeQ/

 $('#my_link').text( function(i,txt) {return txt.replace(/\d+/,'other value'); }); 

This eliminates the need to run the selector twice.

Also, when you get an element by its identifier, it is actually a little faster if you do not specify a tag name.

So instead

 $('a#my_link') 

better to do

 $('#my_link') 

as I said above.

+10
source share
 var new_string = $('a#my_link').text().replace(/[0-9]+/, "somethingelse") 

Replace somethingelse , well, something else. :)

+4
source share
 $('a#my_link').text($('a#my_link').text().replace(/\d+/,'something')); 
+2
source share

This will work for prime numbers containing 0 - 9.

 var my_string = $('a#my_link').text().replace(/[0-9]+/, 'replacement'); 

If you need to match more complex numbers, such as decimal and negative numbers, then this will work:

 var my_string = $('a#my_link').text().replace(/-?[0-9]*\.?[0-9]+/, 'replacement'); 

If you need to match even harder things, like exponential notation or numbers with commas, you need to change the regular expression accordingly - how you do it will depend on how strictly you want to check.

+1
source share

First you need to go through each word, separating the space character with the split () function and send the result to an array of strings.

Once you do, check each word for a number. If you find the number, use the jquery replaceWith () function: http://api.jquery.com/replaceWith/

Hope this helps.

0
source share

All Articles