繁体   English   中英

正则表达式用一个空格替换多个空格

[英]Regex to replace multiple spaces with a single space

给定一个字符串,例如:

"The dog      has a long   tail, and it     is RED!"

什么样的 jQuery 或 JavaScript 魔法可以用来保持空间只有一个空间最大值?

目标:

"The dog has a long tail, and it is RED!"

鉴于您还想覆盖制表符、换行符等,只需将\s\s+替换为' '

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

如果您真的只想覆盖空格(因此不包括制表符、换行符等),请这样做:

string = string.replace(/  +/g, ' ');

由于您似乎对性能感兴趣,因此我使用 firebug 对这些进行了分析。 这是我得到的结果:

str.replace( /  +/g, ' ' )       ->  380ms
str.replace( /\s\s+/g, ' ' )     ->  390ms
str.replace( / {2,}/g, ' ' )     ->  470ms
str.replace( / +/g, ' ' )        ->  790ms
str.replace( / +(?= )/g, ' ')    -> 3250ms

这是在 Firefox 上,运行 100k 字符串替换。

如果您认为性能是一个问题,我鼓励您使用 firebug 进行自己的分析测试。 众所周知,人类不善于预测程序的瓶颈所在。

(另外,请注意,IE 8 的开发人员工具栏还内置了一个分析器——可能值得检查一下 IE 中的性能。)

var str = "The      dog        has a long tail,      and it is RED!";
str = str.replace(/ {2,}/g,' ');

编辑:如果您希望替换所有类型的空白字符,最有效的方法是:

str = str.replace(/\s{2,}/g,' ');

一个更健壮的方法:如果存在的话,这也会删除初始和尾随空格。 例如:

// NOTE the possible initial and trailing spaces
var str = "  The dog      has a long   tail, and it     is RED!  "

str = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");

// str -> "The dog has a long tail, and it is RED !"

您的示例没有这些空格,但它们也是一个非常常见的场景,并且接受的答案只是将它们修剪成单个空格,例如:“... RED!”,这不是您通常需要的。

这是一种解决方案,尽管它将针对所有空格字符:

"The      dog        has a long tail,      and it is RED!".replace(/\s\s+/g, ' ')

"The dog has a long tail, and it is RED!"

编辑:这可能更好,因为它的目标是一个空格,后跟 1 个或多个空格:

"The      dog        has a long tail,      and it is RED!".replace(/  +/g, ' ')

"The dog has a long tail, and it is RED!"

替代方法:

"The      dog        has a long tail,      and it is RED!".replace(/ {2,}/g, ' ')
"The dog has a long tail, and it is RED!"

我没有单独使用/\s+/ ,因为它会多次替换跨越 1 个字符的空格,并且可能效率较低,因为它的目标超出了必要的范围。

如果有错误,我没有深入测试这些中的任何一个。

此外,如果您要进行字符串替换,请记住将变量/属性重新分配给它自己的替换,例如:

var string = 'foo'
string = string.replace('foo', '')

使用 jQuery.prototype.text:

var el = $('span:eq(0)');
el.text( el.text().replace(/\d+/, '') )

我有这个方法,我把它叫做 Derp 方法,因为没有更好的名字。

while (str.indexOf("  ") !== -1) {
    str = str.replace(/  /g, " ");
}

在 JSPerf 中运行它给出了一些令人惊讶的结果,它击败了一些更复杂的方法编辑原始 JSPerf 链接http://jsperf.com/removing-multiple-spaces/3当时似乎已经死了

如果您不想使用替换,这是一个替代解决方案(在不使用替换 JavaScript 的情况下替换字符串中的空格)

 var str="The dog has a long tail, and it is RED!"; var rule=/\s{1,}/g; str = str.split(rule).join(" "); document.write(str);

更健壮:

function trim(word)
{
    word = word.replace(/[^\x21-\x7E]+/g, ' '); // change non-printing chars to spaces
    return word.replace(/^\s+|\s+$/g, '');      // remove leading/trailing spaces
}

我建议

string = string.replace(/ +/g," ");

只为空间
或者

string = string.replace(/(\s)+/g,"$1");

也可以将多个回报变成一个回报。

还有一种可能:

str.replace( /\s+/g, ' ' )

我知道我迟到了,但我发现了一个很好的解决方案。

这里是:

var myStr = myStr.replace(/[ ][ ]*/g, ' ');

新手的综合未加密答案等。

这适用于像我这样测试你们中的一些人编写的脚本但不起作用的所有傻瓜。

以下 3 个示例是我在以下 3 个网站上删除特殊字符和多余空格所采取的步骤(所有这些都可以正常工作){1. EtaVisa.com 2. EtaStatus.com 3. Tikun.com} 所以我知道这些工作完美。

我们一次将这些与 50 多个链接在一起,没有问题。

// 这删除了特殊字符 + 0-9 并且只允许字母(大写和小写)

function NoDoublesPls1()
{
var str=document.getElementById("NoDoubles1");
var regex=/[^a-z]/gi;
str.value=str.value.replace(regex ,"");
}

// 这删除了特殊字符,只允许使用字母(大写和小写)和 0-9 AND 空格

function NoDoublesPls2()
{
var str=document.getElementById("NoDoubles2");
var regex=/[^a-z 0-9]/gi;
str.value=str.value.replace(regex ,"");
}

// 这删除了特殊字符,只允许使用字母(大写和小写)和 0-9 和空格 // 最后的 .replace(/\s\s+/g, " ") 删除了多余的空格 // 当我使用单引号,它不起作用。

function NoDoublesPls3()
{    var str=document.getElementById("NoDoubles3");
var regex=/[^a-z 0-9]/gi;
str.value=str.value.replace(regex ,"") .replace(/\s\s+/g, " ");
}

::NEXT:: Save #3 as a .js // 我叫我的 NoDoubles.js

::NEXT::将您的 JS 包含到您的页面中

 <script language="JavaScript" src="js/NoDoubles.js"></script>

将此包含在您的表单字段中:: 例如

<INPUT type="text" name="Name"
     onKeyUp="NoDoublesPls3()" onKeyDown="NoDoublesPls3()" id="NoDoubles3"/>

所以它看起来像这样

<INPUT type="text" name="Name" onKeyUp="NoDoublesPls3()" onKeyDown="NoDoublesPls3()" id="NoDoubles3"/>

这将删除特殊字符,允许使用单个空格并删除多余的空格。

var string = "The dog      has a long   tail, and it     is RED!";
var replaced = string.replace(/ +/g, " ");

或者,如果您还想替换标签:

var replaced = string.replace(/\s+/g, " ");

Jquery 具有 trim() 函数,它基本上将类似“FOo Bar”的内容转换为“FOo Bar”。

var string = "  My     String with  Multiple lines    ";
string.trim(); // output "My String with Multiple lines"

它更有用,因为它会自动删除字符串开头和结尾的空格。 不需要正则表达式。

是替换没用,string = string.split(/\\W+/);

// 用一个空格替换多个空格

String replacedDisplayName = displayName.replaceAll("\\s{2,}", " ");
var myregexp = new RegExp(/ {2,}/g);

str = str.replace(myregexp,' ');
var text = `xxx  df dfvdfv  df    
                     dfv`.split(/[\s,\t,\r,\n]+/).filter(x=>x).join(' ');

结果:

"xxx df dfvdfv df dfv"

我知道我们必须使用正则表达式,但在一次采访中,我被要求不使用正则表达式。

@slightlytyler 帮助我采用了以下方法。

 const testStr = "I LOVE STACKOVERFLOW LOL"; const removeSpaces = str => { const chars = str.split(''); const nextChars = chars.reduce( (acc, c) => { if (c === ' ') { const lastChar = acc[acc.length - 1]; if (lastChar === ' ') { return acc; } } return [...acc, c]; }, [], ); const nextStr = nextChars.join(''); return nextStr }; console.log(removeSpaces(testStr));

这是适合我的解决方案:

 var text = " Tes ddas dMd WAlkman 3Dsfd ".toLowerCase().replace(/\b\s+/g, " ").replace(/\b\w/g, s => s.toUpperCase()).trimStart().trimEnd(); console.log(text); // result: Tes Ddas Dmd Walkman 3dsfd

我们可以在 sed 系统命令的帮助下使用以下正则表达式。 类似的正则表达式可用于其他语言和平台。

将文本添加到某个文件中说测试

manjeet-laptop:Desktop manjeet$ cat test
"The dog      has a long   tail, and it     is RED!"

我们可以使用以下正则表达式将所有空格替换为单个空格

manjeet-laptop:Desktop manjeet$ sed 's/ \{1,\}/ /g' test
"The dog has a long tail, and it is RED!"

希望这能达到目的

试试这个用一个空格替换多个空格。

<script type="text/javascript">
    var myStr = "The dog      has a long   tail, and it     is RED!";
    alert(myStr);  // Output 'The dog      has a long   tail, and it     is RED!'

    var newStr = myStr.replace(/  +/g, ' ');
    alert(newStr);  // Output 'The dog has a long tail, and it is RED!'
</script>

阅读更多@ 用单个空格替换多个空格

要获得更多控制,您可以使用替换回调来处理该值。

value = "tags:HUNT  tags:HUNT         tags:HUNT  tags:HUNT"
value.replace(new RegExp(`(?:\\s+)(?:tags)`, 'g'), $1 => ` ${$1.trim()}`)
//"tags:HUNT tags:HUNT tags:HUNT tags:HUNT"

此脚本删除单词和修剪之间的任何空白(多个空格、制表符、回车等):

// Trims & replaces any wihtespacing to single space between words
String.prototype.clearExtraSpace = function(){
  var _trimLeft  = /^\s+/,
      _trimRight = /\s+$/,
      _multiple  = /\s+/g;

  return this.replace(_trimLeft, '').replace(_trimRight, '').replace(_multiple, ' ');
};

' mouse pointer touch '.replace(/^\s+|\s+$|(\s)+/g, "$1") 应该可以解决问题!

这对我来说适用于 Python 3

string = "The dog                has a long   tail, and it     is RED!"

while string  != string.replace("  ", ' ', -1):
    string  = string.replace("  ", ' ', -1)

print(string)

我的名字是 Edelcio Junior。 如果您想防止 2 个或更多空格,这是一个很好的解决方案:

<label">Name</label>
<input type="text" name="YourInputName">

<script>
  var field = document.querySelector('[name="YourInputName"]');

  field.addEventListener('keyup', function (event) {
    var userName = field.value;
    userName = userName.replace(/\s{2,}/g, ' ');
    field.value = userName;
  });
</script>

 var field = document.querySelector('[name="YourInputName"]'); field.addEventListener('keyup', function (event) { var userName = field.value; userName = userName.replace(/\s{2,}/g, ' '); field.value = userName; });
 <!DOCTYPE html> <html lang="en"> <head> <title>Your-title</title> <meta charset="utf-8"> </head> <body> <form> <label>Name</label> <input type="text" name="YourInputName"> </form> </body> </html>

let nameCorrection = function (str) {
  let strPerfect = str.replace(/\s+/g, " ").trim();
  let strSmall = strPerfect.toLowerCase();
  let arrSmall = strSmall.split(" ");
  let arrCapital = [];
  for (let x of arrSmall.values()) {
    arrCapital.push(x[0].toUpperCase() + x.slice(1));
  }

  let result = arrCapital.join(" ");
  console.log(result);
};
nameCorrection("Pradeep kumar dHital");

def removeblanks(text): return re.sub(r'\s\s+'," ",text)我正在处理包含大量重复空格的大型文本数据。 上面的 RE 对我有用。 所有重复的空格都被一个空格替换。

使用 nodepad++ 函数,下面的正则表达式对我来说很好,

查找: {1}\K\s+
替换: leave it empty

暂无
暂无

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

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