javascript字符串删除空格和连字符

时间:2021-06-01 21:41:47

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 ?

我该如何一次性完成?

3 个解决方案

#1


20  

Use alternation:

使用交替:

var new_string = string.replace(/-|\s/g,"");

a|b will match either a or b, so this matches both hyphens and whitespace.

a | b将匹配a或b,因此匹配连字符和空格。

Example:

例:

> "hyphen-containing string".replace(/-|\s/g,"")
'hyphencontainingstring'

#2


5  

You have to use:

你必须使用:

 var new_string = string.replace(/[-\s]/g,"")

/-\s/ means hyphen followed by white space.

/ - \ s /表示连字符后跟空格。

#3


4  

Use This for Hyphens

用于连字符

var str="185-51-671";
var newStr = str.replace(/-/g, "");

White Space

白色空间

var Actuly = newStr.trim();

#1


20  

Use alternation:

使用交替:

var new_string = string.replace(/-|\s/g,"");

a|b will match either a or b, so this matches both hyphens and whitespace.

a | b将匹配a或b,因此匹配连字符和空格。

Example:

例:

> "hyphen-containing string".replace(/-|\s/g,"")
'hyphencontainingstring'

#2


5  

You have to use:

你必须使用:

 var new_string = string.replace(/[-\s]/g,"")

/-\s/ means hyphen followed by white space.

/ - \ s /表示连字符后跟空格。

#3


4  

Use This for Hyphens

用于连字符

var str="185-51-671";
var newStr = str.replace(/-/g, "");

White Space

白色空间

var Actuly = newStr.trim();