Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery removing '-' character from string

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('-', ''); 
like image 902
Riain McAtamney Avatar asked Jun 01 '10 13:06

Riain McAtamney


People also ask

How do I remove the first character of a string in jQuery?

You can also remove the first character from a string using substring method. let input = "codehandbook" function removeCharacter(str){ return str. substring(1) } let output = removeCharacter(input); console. log(`Output is ${output}`);

How do I remove a character from a string?

Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.


1 Answers

$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 ); 
like image 155
user113716 Avatar answered Oct 14 '22 06:10

user113716