[英]How to remove a space before a dot?
I try to add a dot in the middle of sentence, before a capital letter.我尝试在句子中间加一个点,在大写字母之前。 I tried this:
我试过这个:
function correctSentences(str){
s = str.replace(/([A-Z])/g,'. $1').trim();
return s;
}
correctSentences(" avi loves pizza Dani loves cola ");
The output is: output 是:
"avi loves pizza . Dani loves cola"
how can i remove the space before the dot?如何删除点之前的空格? thank you!
谢谢你!
Add \s
in regex在正则表达式中添加
\s
function correctSentences(str){ s = str.replace(/(\s[AZ])/g,'.$1').trim(); return s; } console.log(correctSentences(" avi loves pizza Dani loves cola "));
I would use this version:我会使用这个版本:
function correctSentences(str) { return str.replace(/\s+(?=[AZ])/g, '. ').trim(); } var input = " avi loves pizza Dani loves cola "; var output = correctSentences(input); console.log(input + "\n" + output);
The regex logic here says to:这里的正则表达式逻辑说:
\s+ match one or more whitespace characters
(?=[A-Z]) then assert (but do not consume) that what follows is a capital letter
We replace with dot, to end the previous sentence, followed by two spaces, to separate from the start of the next sentence.我们用点代替,结束上一句,后跟两个空格,与下一句的开头隔开。
I propose:我提议:
function correctSentences(str){ return str.replace(/(?=\b\s+[AZ])/g, '.').trim(); } const result = correctSentences(" avi loves pizza. Bob loves pizza Dani loves cola "); console.log(result);
Also it prevents to add an additional .
它还可以防止添加额外的
.
if there's already a .
如果已经有一个
.
exists.存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.