68

使用javascript会this contains spaces 变成什么功能 ?this contains spaces

我使用类似的 SO 问题尝试了以下操作,但无法使其正常工作。

var string = " this contains   spaces ";

newString = string.replace(/\s+/g,''); // "thiscontainsspaces"
newString = string.replace(/ +/g,'');  //"thiscontainsspaces"

有没有一种简单的纯javascript方法来完成这个?

4

11 回答 11

161

你很近。

请记住,用第二个参数replace 替换找到的文本。所以:

newString = string.replace(/\s+/g,''); // "thiscontainsspaces"

查找任意数量的连续空格并删除它们。尝试用一个空格代替它们!

newString = string.replace(/\s+/g,' ').trim();
于 2013-06-07T01:04:55.173 回答
25
string.replace(/\s+/g, ' ').trim()
于 2013-06-07T01:04:28.483 回答
12

试试这个,这将替换字符串中的 2 个或 2+ 个空格。

const string = " this contains   spaces ";    
string.replace(/\s{2,}/g, ' ').trim() 
输出
this contains spaces
于 2019-09-18T17:14:07.053 回答
8

我想出了一种方法,但很好奇是否有更好的方法......

string.replace(/\s+/g,' ').trim()
于 2013-06-07T01:04:29.547 回答
6

我遇到了同样的问题,我这样修复了

Text = Text.replace(/ {1,}/g," ");
Text = Text.trim();
于 2020-01-29T18:21:07.613 回答
3

我认为图像总是说明它很好,基本上你看到正则表达式中的正则表达式\s含义是空格。说它可以是+倍数。/g它在全局范围内看起来的符号(默认情况下替换第一个出现而不/g添加的符号)。如果存在,修剪将删除最后一个和第一个空格。

最后,要删除多余的空格,您将需要以下代码:

newString = string.replace(/\s+/g,' ').trim();

在此处输入图像描述

于 2021-08-27T10:42:10.573 回答
3

我们可以使用以下方法来删除句子/单词中的多余空格。

sentence.split(' ').filter(word => word).join(' ')
于 2021-09-19T08:23:42.703 回答
0

原始 Javascript 解决方案:

var str = '  k                                     g  alok   deshwal';
function removeMoreThanOneSpace() {
    String.prototype.removeSpaceByLength=function(index, length) {
        console.log("in remove", this.substr(0, index));
        return this.substr(0, index) + this.substr(length);
    }
    for(let i  = 0; i < str.length-1; i++) {
        if(str[i] === " " && str[i+1] === " ") {
            str = str.removeSpaceByLength(i, i+1);
            i = i-1;
        }
    }
    return str;
}
console.log(removeMoreThanOneSpace(str));
于 2019-12-28T05:24:34.390 回答
0
var s=" i am a student "
var r='';
console.log(s);
var i,j;
j=0;
for(k=0; s[k]!=undefined; k++);// to calculate the length of a string

for(i=0;i<k;i++){
if(s[i]!==' '){
for(;s[i]!==' ';i++){
r+=s[i];
}
r+=' ';
}
}
console.log(r);
于 2020-10-20T06:03:43.910 回答
0

// Here my solution

const trimString = value => {

  const allStringElementsToArray = value.split(''); 
  // transform "abcd efgh" to ['a', 'b', 'c', 'd',' ','e', 'f','g','h']

  const allElementsSanitized = allStringElementsToArray.map(e => e.trim());
  // Remove all blank spaces from array

  const finalValue = allElementsSanitized.join('');
  // Transform the sanitized array ['a','b','c','d','e','f','g','h'] to 'abcdefgh'

  return finalValue;
}

于 2022-02-18T19:37:40.947 回答
-1
//This code remove extra spaces with out using "string objectives" 
      s="                 This Is   Working On      Functions  "
            console.log(s)
            final=""; 
            res='';
        function result(s) {
         for(var i=0;i<s.length;i++)
            {    
                if(!(final==""&&s[i]==" ")&&!(s[i]===" "&& s[i+1] ===" ")){ 
              final+=s[i]; 
               }
            }
           
            console.log(final);
        }
        result(s);
        
于 2020-10-21T05:10:34.770 回答