简体   繁体   English

如何去除字符串中多余的空格?

[英]How to remove the extra spaces in a string?

What function will turn this contains spaces into this contains spaces using javascript?什么 function 会将this contains spaces变成this contains spaces using javascript?

I've tried the following, using similar SO questions, but could not get this to work.我已经尝试了以下,使用类似的 SO 问题,但无法让它工作。

var string = " this contains   spaces ";

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

Is there a simple pure javascript way to accomplish this?有没有简单的纯 javascript 方法来完成这个?

You're close.你很接近。

Remember that replace replaces the found text with the second argument.请记住, replace第二个参数替换找到的文本。 So:所以:

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

Finds any number of sequential spaces and removes them.查找任意数量的连续空格并删除它们。 Try replacing them with a single space instead!尝试用一个空格代替它们!

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

Try this one, this will replace 2 or 2+ white spaces from string.试试这个,这将替换字符串中的 2 或 2+ 个空格。

const string = " this contains   spaces ";    
string.replace(/\s{2,}/g, '').trim() 

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

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

I got the same problem and I fixed like this我遇到了同样的问题,我是这样解决的

Text = Text.replace(/ {1,}/g," ");
Text = Text.trim();

I think images always explain it's good, basically what you see that the regex \\s meaning in regex is whitespace.我认为图像总是可以解释它的好处,基本上你看到的正则表达式\\s在正则表达式中\\s含义是空格。 the + says it's can be multiply times. +表示它可以成倍增加。 /g symbol that it's looks globally (replace by default looks for the first occur without the /g added). /g符号,它看起来是全局的(默认情况下替换查找没有添加/g的第一次出现)。 and the trim will remove the last and first whitespaces if exists.如果存在,修剪将删除最后一个和第一个空格。

Finally, To remove extra whitespaces you will need this code:最后,要删除多余的空格,您将需要以下代码:

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

在此处输入图片说明

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

sentence.split(' ').filter(word => word).join(' ')

Raw Javascript Solution:原始 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));
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);

// 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;
}

I have tried regex to solve this problem:我试过正则表达式来解决这个问题:

let temp=text.replace(/\s{2,}/g, ' ').trim() 
console.log(temp);

input="Plese complete your work on Time" input="请按时完成你的工作"

output="Please complete your work on Time" output="请按时完成你的工作"

//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);
        

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM