99

I have a string "-123445". Is it possible to remove the '-' character from the string?

I have tried the following but to no avail:

$mylabel.text("-123456");
$mylabel.text().replace('-', '');
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Riain McAtamney
  • 6,342
  • 17
  • 49
  • 62

3 Answers3

184
$mylabel.text( $mylabel.text().replace('-', '') );

Since text() gets the value, and text( "someValue" ) sets the value, you just place one inside the other.

Would be the equivalent of doing:

var newValue = $mylabel.text().replace('-', '');
$mylabel.text( newValue );

EDIT:

I hope I understood the question correctly. I'm assuming $mylabel is referencing a DOM element in a jQuery object, and the string is in the content of the element.

If the string is in some other variable not part of the DOM, then you would likely want to call the .replace() function against that variable before you insert it into the DOM.

Like this:

var someVariable = "-123456";
$mylabel.text( someVariable.replace('-', '') );

or a more verbose version:

var someVariable = "-123456";
someVariable = someVariable.replace('-', '');
$mylabel.text( someVariable );
user113716
  • 318,772
  • 63
  • 451
  • 440
  • yip $mylabel is referencing a DOM element. I've tried this and it works perfectly. Thanks for your help. – Riain McAtamney Jun 01 '10 at 14:12
  • 9
    Just in case you want to remove all occurrences of a string, instead of just the first one, you can use: $mylabel.text().replace(/-/g, ''); – leticia Aug 30 '13 at 14:08
12

If you want to remove all - you can use:

.replace(new RegExp('-', 'g'),"")
Elnaz
  • 2,854
  • 3
  • 29
  • 41
9
$mylabel.text("-123456");
var string = $mylabel.text().replace('-', '');

if you have done it that way variable string now holds "123456"

you can also (i guess the better way) do this...

$mylabel.text("-123456");
$mylabel.text(function(i,v){
   return v.replace('-','');
});
Reigel Gallarde
  • 64,198
  • 21
  • 121
  • 139