Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a number in a string with jquery

Tags:

jquery

I have a string which has a number in it that I would like to replace with another number.

ie

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

I know there is only going to be 1 number in this string.

I can get this far:

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

But basically I don't know how to then perform a search on my_string for a numeral and replace that number with something else.

Is that possible with jQuery?

Thanks for any ideas.

like image 514
willdanceforfun Avatar asked Jul 31 '10 13:07

willdanceforfun


People also ask

How do you replace an element with another in jQuery?

We can replace HTML elements using the jQuery . replaceWith() method. With the jQuery replaceWith() method, we can replace each element in the set of matched elements with the provided new content and return the set of elements that were removed.

How do I replace a character in a string?

The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name. replace(old_string, new_string) with old_string being the substring you'd like to replace and new_string being the substring that will take its place.


2 Answers

Many jQuery methods like .text() can accept a function that returns the value to insert.

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

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

This removes the need to run the selector twice.

Also, when you are getting an element by its ID, it is actually a little quicker if you do not include the tag name.

So instead of

$('a#my_link')

it is better to do

$('#my_link')

as I did above.

like image 91
user113716 Avatar answered Sep 25 '22 11:09

user113716


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

Replace somethingelse with, well, something else. :)

like image 20
Krevan Avatar answered Sep 24 '22 11:09

Krevan