javascript javascript字符串删除空格和连字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24859717/
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
javascript string remove white spaces and hyphens
提问by Alon
I would like to remove white spaces and hyphens from a given string.
我想从给定的字符串中删除空格和连字符。
var string = "john-doe alejnadro";
var new_string = string.replace(/-\s/g,"")
Doesn't work, but this next line works for me:
不起作用,但下一行对我有用:
var new_string = string.replace(/-/g,"").replace(/ /g, "")
How do I do it in one go ?
如何一次性完成?
回答by Michael Homer
Use alternation:
使用交替:
var new_string = string.replace(/-|\s/g,"");
a|b
will match eithera
or b
, so this matches both hyphens and whitespace.
a|b
将匹配任何a
或b
,所以这两个连字符和空格相匹配。
Example:
例子:
> "hyphen-containing string".replace(/-|\s/g,"")
'hyphencontainingstring'
回答by anubhava
You have to use:
你必须使用:
var new_string = string.replace(/[-\s]/g,"")
/-\s/
means hyphen followed by white space.
/-\s/
表示连字符后跟空格。
回答by cracker
Use This for Hyphens
将其用于连字符
var str="185-51-671";
var newStr = str.replace(/-/g, "");
White Space
空白
var Actuly = newStr.trim();