我想判断一个字符串中,“.”后面是否没有空格
我尝试了嵌套的 if 语句,但它不起作用。我想我错过了一些非常简单的东西。
此外,我读到 Regex 可能会这样做,但我无法理解语法。
(function() {
'use strict';
var invocationInitial = document.getElementById('spokenNames');
if(invocationInitial) {
var invocation = invocationInitial.innerHTML.trim();
}
var counter = 1;
var message = '';
if(invocation.indexOf('.') !== -1) {
if(/\s/.test(invocationInitial) === false)
{
message = counter + ". No dot in string without subsequent whitespace";
counter = counter +1;
}
}
if(message) {
alert(message);
}
})();
如果“invocationInitial”不每个出现的点 (.) 后跟一个空格,则应显示浏览器警告(“消息”)。
这里引入var counter,因为在完整版中,会根据不同的情况显示多种浏览器警告。
最佳答案
这里您需要的 RegEx 非常简单:/\.\S/
。那就是说“匹配一个不后跟空白字符的点”。请注意,\s
表示“匹配空白字符”,而 \S
(大写 S)表示“匹配任何非空白字符”。
所以你可以简单地这样做:
if (/\.\S/.test(invocation)) {
// There's a dot followed by non-whitespace!
}
else {
// There is no dot followed by non-whitespace.
}
关于javascript - 通过 "."识别 "if ... if"并且字符串中没有空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56638709/