tags:

views:

79

answers:

5

Hi there,

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.

A: 

This will work for simple natural 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 decimals and negative numbers, then this would work:

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

If you need to match more complex still, like exponential notation, or numbers with commas, you'd need to modify the regex appropriately -- how you do that will depend on how stringently you want to validate.

Jhong
That's not what the OP asked. It will return the first character of the number ('3' in this case); he wants to replace the **whole** number with another number.
Krevan
Thanks, edited :-) However the regex will match the whole number, not the first digit.
Jhong
+2  A: 
var new_string = $('a#my_link').text().replace(/[0-9]+/, "somethingelse")

Replace somethingelse with, well, something else. :)

Krevan
+2  A: 
$('a#my_link').text($('a#my_link').text().replace(/\d+/,'something'));
David
`$('a#my_link').text($(this).text().replace(/\d+/,'something'));` should be even better
Mikulas Dite
@Mikulas Dite - Try it and you'll discover that `this` in your example isn't referring to the element you think it is. ;)
Gert G
A: 

First you need to loop through each word by splitting off on the space character using the split() function and send the result to a string array.

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

Hope that helps.

Aelux
+3  A: 

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.

patrick dw
Now, this is a solution that doesn't require two element grabs. Nice.
Gert G
Thanks @Gert. :o)
patrick dw
@patrick - I'll need to get into the habit of using functions like that. It's a really neat way when replacing stuff.
Gert G