如果我有一个包含多个空格的字符串:
Be an excellent person
使用 JavaScript / 正则表达式,如何删除多余的内部空格,使其变为:
Be an excellent person
Be an excellent person
使用 JavaScript / 正则表达式,如何删除多余的内部空格,使其变为:
Be an excellent person
您可以使用正则表达式:/\s{2,}/g
:
var s = "Be an excellent person"
s.replace(/\s{2,}/g, ' ');
var t = 'Be an excellent person';
t.replace(/ {2,}/g, ' ');
// Output: "Be an excellent person"
var text = 'Be an excellent person';
alert(text.replace(/\s\s+/g, ' '));
您可以使用以下方法去除双空格:
var text = 'Be an excellent person';
alert(text.replace(/\s\s+/g, ' '));
Snippet:
var text = 'Be an excellent person';
//Split the string by spaces and convert into array
text = text.split(" ");
// Remove the empty elements from the array
text = text.filter(function(item){return item;});
// Join the array with delimeter space
text = text.join(" ");
// Final result testing
alert(text);