给定一个这样的字符串:
"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!"
当前回答
一种更健壮的方法:如果存在初始空格和尾随空格,则该方法也会删除它们。例如:
// NOTE the possible initial and trailing spaces
var str = " The dog has a long tail, and it is RED! "
str = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
// str -> "The dog has a long tail, and it is RED !"
你的例子没有这些空格,但它们也是一个非常常见的场景,而公认的答案只是把它们精简成单个空格,比如:“the…红色!,这不是您通常需要的。
其他回答
一种更健壮的方法:如果存在初始空格和尾随空格,则该方法也会删除它们。例如:
// NOTE the possible initial and trailing spaces
var str = " The dog has a long tail, and it is RED! "
str = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
// str -> "The dog has a long tail, and it is RED !"
你的例子没有这些空格,但它们也是一个非常常见的场景,而公认的答案只是把它们精简成单个空格,比如:“the…红色!,这不是您通常需要的。
我建议
string = string.replace(/ +/g," ");
对于空格或
string = string.replace(/(\s)+/g,"$1");
还可以将多个退货转换为单个退货。
还有一种可能:
str.replace( /\s+/g, ' ' )
鼠标指针碰到.replace(美元/ ^ \ s + | \ s + | (\ s) + / g, 1美元)应该做的诀窍!
Def removeblanks(text):返回re.sub(r'\s\s+'," ",text) 我正在处理一个有很多重复空格的大型文本数据。 上面的RE对我很有用。所有重复的空格都被一个空格取代。