jQuery jQuery从字符串中删除'-'字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2950357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:36:38  来源:igfitidea点击:

jQuery removing '-' character from string

jquerystringreplace

提问by Riain McAtamney

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

我有一个字符串“-123445”。是否可以从字符串中删除“-”字符?

I have tried the following but to no avail:

我尝试了以下但无济于事:

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

回答by user113716

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

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

由于text()获取值并text( "someValue" )设置值,您只需将一个放在另一个中。

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 $mylabelis referencing a DOM element in a jQuery object, and the string is in the content of the element.

我希望我正确理解了这个问题。我假设$mylabel在 jQuery 对象中引用 DOM 元素,并且字符串在元素的内容中。

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 beforeyou insert it into the DOM.

如果字符串位于不属于 DOM 的某个其他变量中,那么您可能希望将其插入 DOM之前.replace()针对该变量调用该函数。

Like this:

像这样:

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

or a more verbose version:

或更详细的版本:

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

回答by Elnaz

If you want to remove all -you can use:

如果你想删除所有-你可以使用的:

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

回答by Reigel

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

if you have done it that way variable stringnow holds "123456"

如果你这样做了,变量string现在保持不变"123456"

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

你也可以(我想更好的方法)这样做......

$mylabel.text("-123456");
$mylabel.text(function(i,v){
   return v.replace('-','');
});