如何在 javascript 中组合 str.replace() 表达式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7990879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:56:12  来源:igfitidea点击:

How to combine str.replace() expressions in javascript?

javascriptstringreplace

提问by Andy Lobel

I want to combine all them expressions into one and haven't got a clue how to do it, it needs to remove the end white-space and remove the beginning white-space but shorten white-space between two words to only one (if there's more than one). Thanks

我想将所有这些表达式合并为一个,但不知道该怎么做,它需要删除结尾的空格并删除开头的空格,但将两个单词之间的空格缩短为一个(如果不止一个)。谢谢

var _str = document.contact_form.contact_name.value;
name_str = _str.replace(/\s+/g,' ');
str_name = name_str.replace(/\s+$/g,'');
name = str_name.replace(/^\s+/g,'');
document.contact_form.contact_name.value = name;

回答by Mark Byers

You can combine the second two into a single regular expression:

您可以将后两个组合成一个正则表达式:

name = _str.replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '');

You could also look at jQuery's trimmethod.

您还可以查看 jQuery 的trim方法。

Description: Remove the whitespace from the beginning and end of a string.

描述:删除字符串开头和结尾的空格。

回答by John Gathogo

document.contact_form.contact_name.value = _str.replace(/\s+/g,' ')..replace(/\s+$/g,'').replace(/^\s+/g,'');

回答by nnnnnn

var name = _str.replace(/\s+$|^\s+/g,'').replace(/\s+/g,' '); 

You can use the |character in your regular expression to match the sub-expression on either side of it, and you can chain multiple calls to .replace().

您可以使用|正则表达式中的字符来匹配其任一侧的子表达式,并且可以将多个调用链接到.replace().

By the way, don't forget to declare all of your variables with var.

顺便说一句,不要忘记用var.

回答by David O'Riva

Looks to me like it's time to define function compactify(str). Even if you could cram all of that into one RegEx, the result would be difficult to read and worse to maintain.

在我看来,是时候定义function compactify(str). 即使您可以将所有这些都塞进一个 RegEx,结果将难以阅读并且更难以维护。