给定一个这样的字符串:
"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!"
当前回答
为了获得更多的控制,您可以使用replace回调来处理该值。
value = "tags:HUNT tags:HUNT tags:HUNT tags:HUNT"
value.replace(new RegExp(`(?:\\s+)(?:tags)`, 'g'), $1 => ` ${$1.trim()}`)
//"tags:HUNT tags:HUNT tags:HUNT tags:HUNT"
其他回答
var string = "The dog has a long tail, and it is RED!";
var replaced = string.replace(/ +/g, " ");
或者如果你也想替换制表符:
var replaced = string.replace(/\s+/g, " ");
更健壮的:
function trim(word) { word = word.replace(/[^\x21-\x7E]+/g, ' '); // change non-printing chars to spaces return word.replace(/^\s+|\s+$/g, ''); // remove leading/trailing spaces }
var myregexp = new RegExp(/ {2,}/g);
str = str.replace(myregexp,' ');
//将多个空格替换为一个空格
String replacedDisplayName = displayName.replaceAll("\\s{2,}", " ");
var text = `xxx df dfvdfv df
dfv`.split(/[\s,\t,\r,\n]+/).filter(x=>x).join(' ');
结果:
"xxx df dfvdfv df dfv"