Javascript 如何替换Javascript中的子字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4410425/
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-23 12:18:16  来源:igfitidea点击:

How to replace substring in Javascript?

javascript

提问by Mohan Ram

To replace substring.But not working for me...

替换子字符串。但对我不起作用......

var str='------check';

str.replace('-','');

Output:-----check

输出:-----检查

Jquery removes first '-' from my text. I need to remove all hypens from my text. My expected output is 'check'

Jquery 从我的文本中删除第一个 '-'。我需要从我的文本中删除所有连字符。我的预期输出是“检查”

回答by ehmad11

simplest:

最简单:

str = str.replace(/-/g, ""); 

回答by jAndy

Try this instead:

试试这个:

str = str.replace(/-/g, '');

.replace()does not modify the original string, but returns the modified version.
With the gat the end of /-/gall occurences are replaced.

.replace()不修改原始字符串,而是返回修改后的版本。
g结束/-/g所有出现的情况都被替换。

回答by John Giotta

str.replace(/\-/g, '');

The regex g flag is global.

regex g 标志是全局的。

回答by simshaun

You can write a short function that loops through and replaces all occurrences, or you can use a regex.

您可以编写一个循环遍历并替换所有出现的短函数,或者您可以使用正则表达式。

var str='------check';

document.write(str.replace(/-+/g, ''));