给定一个这样的字符串:
"The dog has a long tail, and it is RED!"
什么样的jQuery或JavaScript魔法可以用来保持空间只有一个最大空间?
目标:
"The dog has a long tail, and it is RED!"
给定一个这样的字符串:
"The dog has a long tail, and it is RED!"
什么样的jQuery或JavaScript魔法可以用来保持空间只有一个最大空间?
目标:
"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>
阅读更多@用单个空格替换多个空格
其他回答
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");
这是一种解决方案,尽管它将针对所有空格字符:
"The dog has a long tail, and it is RED!".replace(/\s\s+/g, ' ')
"The dog has a long tail, and it is RED!"
编辑:这可能更好,因为它的目标是一个空格后面跟着一个或多个空格:
"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个字符的空格,而且可能效率较低,因为它的目标超过了必要的范围。
我没有深入测试任何这些,所以如果有bug,我就不知道了。
另外,如果你要做字符串替换,记得重新分配变量/属性到它自己的替换,例如:
var string = 'foo'
string = string.replace('foo', '')
使用jQuery.prototype.text:
var el = $('span:eq(0)');
el.text( el.text().replace(/\d+/, '') )
Def removeblanks(text):返回re.sub(r'\s\s+'," ",text) 我正在处理一个有很多重复空格的大型文本数据。 上面的RE对我很有用。所有重复的空格都被一个空格取代。
我有一个方法,我叫它Derp方法因为没有更好的名字。
while (str.indexOf(" ") !== -1) {
str = str.replace(/ /g, " ");
}
在JSPerf中运行它会得到一些令人惊讶的结果,它击败了一些更复杂的方法EDIT原始JSPerf链接http://jsperf.com/removing-multiple-spaces/3当时似乎已经死了
使用nodepad++函数,下面的regex对我来说很好,
发现:{1}\ \ s + K 替换:留空