从文本中删除所有空格

Cec*_*ore 532 javascript jquery

可能重复:
用'+'替换字符串中的所有空格

$("#topNav" + $("#breadCrumb2nd").text().replace(" ", "")).addClass("current");
Run Code Online (Sandbox Code Playgroud)

这是我的代码中的一个片段.我想在获取另一个ID的文本属性后向ID添加一个类.这个问题,是持有我需要的文本的ID,包含字母之间的间隙.

我希望删除白色空格.我试过了TRIM(),REPLACE()但这只是部分有效.该REPLACE()只删除第一个空间.

Fli*_*mzy 1229

你必须告诉replace()重复正则表达式:

.replace(/ /g,'')
Run Code Online (Sandbox Code Playgroud)

字是指通过重复整个字符串搜索.在此处阅读此处以及JavaScript中提供的其他RegEx修饰符.

如果要匹配所有空格,而不仅仅是文字空格字符,请\s改用:

.replace(/\s/g,'')
Run Code Online (Sandbox Code Playgroud)

  • Coffeescript会因为一些可怕的原因而抱怨这个正则表达式.相反,我必须继续使用`.replace(/\s +/g,'')`这对我来说完全没问题. (28认同)
  • 如果你想实现类似ruby的string.strip方法,它返回一个删除了前导和尾随空格的字符串的副本,这应该有效:`x ="在```y = x.replace之前和之后的许多空格(/(^\s + |\s + $)/ g,"")``^\s`表示字符串开头后的空格,`\ s $`表示字符串末尾的空格,`| | `适用于组中的/或组中,并且上面的注释中解释了`g`修饰符.在每个`\ s`之后还需要`+`量词,因为你想要捕获一个或多个空格实例. (7认同)

Pan*_*lis 290

.replace(/\s+/, "") 
Run Code Online (Sandbox Code Playgroud)

替换第一个空格,包括空格,制表符和新行.

要替换字符串中的所有空格,您需要使用全局模式

.replace(/\s/g, "")
Run Code Online (Sandbox Code Playgroud)

  • 第一个不删除**所有**空格(它只删除第一组空格/新行/标签),第二个是OK.演示:http://regex101.com/r/wX8rF2/3 (11认同)
  • .replace(/\s +/g,'') (4认同)

Bal*_*aji 22

正则表达式用于删除空格

\s+
Run Code Online (Sandbox Code Playgroud)

或者

[ ]+
Run Code Online (Sandbox Code Playgroud)

var str = "Visit Microsoft!";
var res = str.replace(/\s+/g, "");
console.log(res);
Run Code Online (Sandbox Code Playgroud)

删除字符串开头的所有空格

^[ ]+
Run Code Online (Sandbox Code Playgroud)

删除字符串末尾的所有空格

[ ]+$
Run Code Online (Sandbox Code Playgroud)

var str = "Visit Microsoft!";
var res = str.replace(/[ ]+/g, "");
console.log(res);
Run Code Online (Sandbox Code Playgroud)

    var mystring="fg gg";
   console.log(mystring.replaceAll(' ',''))
Run Code Online (Sandbox Code Playgroud)


cam*_*777 11

现在你可以使用“replaceAll”:

console.log(' a b    c d e   f g   '.replaceAll(' ',''));
Run Code Online (Sandbox Code Playgroud)

将打印:

abcdefg
Run Code Online (Sandbox Code Playgroud)

但不适用于所有可能的浏览器:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll

  • 我还注意到“replaceAll”方法的运行速度几乎是正则表达式解决方案的两倍。除非您处理的数据量非常大,否则这并不是很重要,但很高兴知道这一点。 (4认同)
  • 请求是替换所有空白。这仅替换文字空格。 (3认同)

Asi*_*kib 10

** 100% 工作

使用replace(/ +/g,'_')

let text = "I     love you"
text = text.replace( / +/g, '_') // replace with underscore ('_')

console.log(text) // I_love_you
Run Code Online (Sandbox Code Playgroud)


Irf*_*ani 8

我不明白为什么我们需要在这里使用正则表达式,而我们可以简单地使用replaceAll

let result = string.replaceAll(' ', '')
Run Code Online (Sandbox Code Playgroud)

result将存储string没有空格


Alb*_*res 7

String.prototype.replace如其他答案中所述,使用正则表达式当然是最好的解决方案。

但是,为了好玩,您还可以使用String.prototype.splitand删除文本中的所有空格String.prototype.join

const text = ' a b    c d e   f g   ';
const newText = text.split(/\s/).join('');

console.log(newText); // prints abcdefg
Run Code Online (Sandbox Code Playgroud)