给定一个这样的字符串:
"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!"
当前回答
我有一个方法,我叫它Derp方法因为没有更好的名字。
while (str.indexOf(" ") !== -1) {
str = str.replace(/ /g, " ");
}
在JSPerf中运行它会得到一些令人惊讶的结果,它击败了一些更复杂的方法EDIT原始JSPerf链接http://jsperf.com/removing-multiple-spaces/3当时似乎已经死了
其他回答
鼠标指针碰到.replace(美元/ ^ \ s + | \ s + | (\ s) + / g, 1美元)应该做的诀窍!
全面的未加密的回答新手等。
这是写给所有像我这样的傻瓜,他们测试了你们中一些人写的不工作的脚本。
以下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个and空格 //结尾的.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, " ");
}
:::: 将#3保存为.js //我将我的命名为NoDoubles.js
:::: 将JS包含在页面中
<script language="JavaScript" src="js/NoDoubles.js"></script>
包括在你的表单字段::such as
<INPUT type="text" name="Name"
onKeyUp="NoDoublesPls3()" onKeyDown="NoDoublesPls3()" id="NoDoubles3"/>
它看起来是这样的
<INPUT type="text" name="Name" onKeyUp="NoDoublesPls3()" onKeyDown="NoDoublesPls3()" id="NoDoubles3"/>
这将删除特殊字符,允许单个空格和删除额外的空格。
我知道我们必须使用正则表达式,但在一次采访中,我被要求不要使用正则表达式。
@slightlytyler帮助我提出了下面的方法。
const testStr = "I LOVE STACKOVERFLOW LOL"; const removeSpaces = str => { Const chars = str.split("); const nextChars = char .reduce( (acc, c) => { If (c === ' ') { const lastChar = acc[acc.]长度- 1]; if (lastChar === ' ') { 返回acc; } } 返回[…acc, c]; }, [], ); const nextStr = nextchar .join("); 返回nextStr }; console.log (removeSpaces (testStr));
尝试用一个空格替换多个空格。
<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>
阅读更多@用单个空格替换多个空格
Def removeblanks(text):返回re.sub(r'\s\s+'," ",text) 我正在处理一个有很多重复空格的大型文本数据。 上面的RE对我很有用。所有重复的空格都被一个空格取代。