Javascript:如何用单个替换多个空格 [英] Javascript: how to replace multiple spaces with single

查看:121
本文介绍了Javascript:如何用单个替换多个空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在输入中我写了多个空格的任何句子,点击Space Remover按钮后,我需要用单个替换多个空格并用h1标签显示它。



我尝试了什么:



我试过这样的,但它不起作用。



In input i write any sentence with multiple spaces,after clicking on Space Remover button,i need to replace that multiple spaces with single and show it in h1 tag.

What I have tried:

I have tried like this, but it's not working.

<input id="bar" type="text" placeholder="Type a sentence...">
		<button onclick="spaceremover()">Space Remover</button>
		<h1 id="result1"></h1>


function spaceremover(){
	var a = document.getElementById("bar").value;
	for(var i = 0; i < a.length;i++){
	a.replace(/\s/g, ' ');	
	}
	document.getElementById("result1").innerHTML = a;
}

推荐答案

您的正则表达式仅替换单个空格字符( \s )只有一个空格。要匹配多个空格的序列,您必须通过附加 + (匹配一个或多个出现)或 {2,} (匹配两个或多个出现)。



使用正则表达式全局选项时也不需要使用循环。



最后, String.prototype .replace() - JavaScript | MDN [ ^ ]函数返回一个新的字符串,其中已执行替换,但不会改变原始字符串



所以使用(未经测试):

Your regex replaces only single white space characters (\s) with a single space. To match sequences of multiple spaces, you have to specify that by appending a + (match one or more occurences) or {2,} (match two or more occurences).

There is also no need to use a loop when using the regex global option.

Finally, the String.prototype.replace() - JavaScript | MDN[^] function returns a new string where the replacement has been performed but does not alter the original string

So use (untested):
function spaceremover(){
    var a = document.getElementById("bar").value;
    document.getElementById("result1").innerHTML = a.replace(/\s{2,}/g, ' ');
}


你可以使用
.replace(/\d+/, '') 






or

.split('/\d+/').join(' ')







.split('  ').join(' ')






or

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








or

var str = "       Hello World!       ";
   alert(str.trim());



这个案例最常用的是


and this one most used in this case

myStr.replace(/  +/g, ' ')





这是值得的。



it would be worthful.


var myStr = 'The     quick   brown  fox';
    alert(myStr);  // Output 'The     quick   brown  fox'
    
    var newStr = myStr.replace(/  +/g, ' ');
    alert(newStr);  // Output 'The quick brown fox'



document.getElementById(result1)。innerHTML = newStr;


document.getElementById("result1").innerHTML = newStr;


这篇关于Javascript:如何用单个替换多个空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆