我有一个代码可以很好地处理字符串末尾的双空格(“”),但不适用于任何字符串中间的空格。
var userInput = prompt("In which city do you live?");
lengthUserInput = userInput.length;
correctName = true;
for (i = 0; i < lengthUserInput; i++) {
if (userInput.slice(i, i + 2) === " ") {
correctName = false;
}
}
if (correctName === false) {
alert("Double spaces are not allowed");
} else {
alert(userInput);
}
答案 0 :(得分:4)
只需检查字符串.includes
是否两个空格:
var userInput = prompt("In which city do you live?");
if (userInput.includes(' ')) {
console.log("Double spaces are not allowed");
} else {
console.log('ok');
}
答案 1 :(得分:3)
您可以使用正则表达式\s{2}
。如果字符串在字符串中的任意位置具有2个连续的空格(true
),则test
方法将返回\s
。 (如果存在> 2个连续空格,则也会返回true)
var userInput = prompt("In which city do you live?");
var incorrectName = /\s{2}/.test(userInput)
if (incorrectName) {
alert("Double spaces are not allowed");
} else {
alert(userInput);
}
答案 2 :(得分:1)
您可以对2个或更多空格使用正则表达式测试:
var userInput = prompt("In which city do you live?");
userInput.test(/ {2,}/g) ? alert('Multiple spaces are not permitted') : alert(userInput)
<!-- begin snippet: js hide: false console: true babel: false -->
如果这样做不是问题,则可以在字符串上使用replace来删除它们的多余空格:
var userInput = prompt("In which city do you live?");
userInput = userInput.replace(/ {2,}/g, ' ')
alert(userInput)
答案 3 :(得分:0)
您可以使用include来查看astring是否包含某些内容。 Includes ref
var str = "Hello world, welcome to the universe.";
var n = str.includes("world");
相同的空格可以使用
var str = "fre refhyt";
var n = str.includes(" ");
console.log(n);
答案 4 :(得分:0)
我喜欢使用替换函数来解决此问题:
var userInput = prompt("In which city do you live?");
if (userInput !== userInput.replace(/ /g, ' ')) {
alert("Double spaces are not allowed");
} else {
alert(userInput);
}
说明:它将用简单的空格替换双精度空格,因此,如果两个字符串都相同:则没有双精度空格。
答案 5 :(得分:0)
如果两个空格的位置不相关,即也应测试字符串的开头/结尾,则也可以使用纯javascript:
if (userInput.indexOf(' ') >= 0) {
alert('some alert message');
}
答案 6 :(得分:0)
为正确解决您的问题,切片将返回两个字符串。但是,您正在将其与一个空格字符的字符串进行比较。因此,当在字符串中间使用双倍空格时,它将永远无法工作。
此比较在字符串末尾使用双倍空格的原因是,在最后一个字符处,切片将仅返回1个空格字符的字符串。
如果与2个空格正确比较,请参见下面的代码段。
var userInput = prompt("In which city do you live?");
lengthUserInput = userInput.length;
correctName = true;
for (i = 0; i < lengthUserInput; i++) {
// Note: the comparison of double space instead of one as shown
if (userInput.slice(i, i + 2) === " ") {
correctName = false;
}
}
if (correctName === false) {
alert("Double spaces are not allowed");
} else {
alert(userInput);
}