i-CONICA
i-CONICA

Reputation: 2379

javascript replace not workings

I've got a problem with replace not working.

alert($('input#membership_edc').next("label").html().replace(/£/g, ""));

The value of the label after the input would be £24.00, but I want to do a math on that value then put it back with the new value. It's not removing the pound sign.

What's wrong? Thanks.

Upvotes: 0

Views: 118

Answers (4)

Phil H
Phil H

Reputation: 20151

The string replace function returns a new string. Strings themselves are immutable in javascript, I think. As Vega has it:

// avoid looking this up twice
var label = alert($('input#membership_edc').next("label"); 
// replace and assign
label.html(label.html().replace(/£/g, ""));

Edit:

To get the numerical value from the string:

var amount = alert($('input#membership_edc').next("label").html().match(/£\s*([-0-9.]+)/)[1];

This matches the numbers etc after the £ (ignoring whitespace), and uses index 1 from the array, containing the contents of the first group match (in the brackets).

" £1.45".match(/£\s*([-0-9.]+)/)[1]; // returns "1.45"

Beware that it is still a string, so you might want to do parseFloat on it.

Upvotes: 0

Alnitak
Alnitak

Reputation: 340045

To read/modify/write use the function parameter version of .html():

$('input#membership_edc').next("label").html(function(index, old) {
    var n = parseFloat(old.replace('£', '');
    return n + 10;
});

would replace '£24.00' with '34'.

Upvotes: 2

rucsi
rucsi

Reputation: 516

Nothing wrong. It is working here. Are you sure your markup is fine?

Upvotes: 0

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79850

You need to set the value returned from the replace. Try below,

var $label = $('input#membership_edc').next("label");
$label.html($label.html().replace(/£/g, ""));

Upvotes: 2

Related Questions