jQuery removing '-' character from string

JqueryStringReplace

Jquery Problem Overview


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('-', '');

Jquery Solutions


Solution 1 - Jquery

$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 );

Solution 2 - Jquery

If you want to remove all - you can use:

.replace(new RegExp('-', 'g'),"")

Solution 3 - Jquery

$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('-','');
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRiain McAtamneyView Question on Stackoverflow
Solution 1 - Jqueryuser113716View Answer on Stackoverflow
Solution 2 - JqueryElnazView Answer on Stackoverflow
Solution 3 - JqueryReigelView Answer on Stackoverflow