简体   繁体   English

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

[英]javascript string remove white spaces and hyphens

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 ? 我该如何一次性完成?

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匹配 ab ,所以这两个连字符和空格相匹配。

Example: 例:

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

You have to use: 你必须使用:

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

/-\\s/ means hyphen followed by white space. /-\\s/表示连字符后跟空格。

Use This for Hyphens 用于连字符

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

White Space 白色空间

var Actuly = newStr.trim();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 创建一个函数来删除JavaScript中字符串中的所有空格? - Create a function to remove all white spaces in string in JavaScript? 使用javascript删除字符串中的所有非字母数字和任何空格 - Remove all non alphanumeric and any white spaces in string using javascript 用连字符替换字符串中的空格 - replacing spaces in a string with hyphens RegEx Javascript - 整个字符串中只有 0-2 个空格或连字符? - RegEx Javascript - Only 0-2 spaces or hyphens in whole string? 尝试检索所有以空格,连字符,单引号或字符串开头的前导大写字符 - Trying to retrieve all leading Capitalized characters preceded with white-spaces, hyphens, apostrophes, or start of the string 在javascript中传递包含空格的字符串 - pass string containing white spaces in javascript Javascript - 按前 2 个空格拆分字符串 - Javascript - Split string by first 2 white spaces JavaScript:除了值中的值之外,如何从JSON字符串中删除所有空格? - JavaScript: how do I remove all the white spaces from a JSON string except the ones in the values? React / Javascript - 从输入字段(搜索栏)中删除字符串两端的空格和单词之间的额外空格 - React / Javascript - Remove white spaces from both ends of a string and extra spaces between words, from a input field (search bar) 从JavaScript字符串中删除空格,但不是所有空格 - Remove spaces from javascript string but not all spaces
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM