[英]Check if a string in an array has white space character in javascript/jquery
I am trying to type a text in a conteneditable div and when I loop through them the for loop as an array and check if there are any white space characters (ie abc de
ie space between the two words it does not recognize them as empty string ).我试图在可替换的 div 中键入文本,当我将它们作为数组循环时,for 循环并检查是否有任何空格字符(即
abc de
ie 两个单词之间的空格,它无法将它们识别为空字符串)。 Please see below code.请看下面的代码。
Script:脚本:
function htmltoBBcode() {
$("#hidden").html($('#textEditor').html());
$("#hidden").html($('#textEditor').html());
var arr=$("#hidden").text();
for(var i=0;i<arr.length;i++)
{
if(arr[i]=='')
{
console.log("i is true"+arr[i]);
}
else{
console.log("i is false"+arr[i]);
}
}
}
In the above code, I am taking the text from the contenteditable div and looping through them, if the arr[i]==''
it should return true
in the console.log
but it keeps returning false always, even though it is an empty string(white space).在上面的代码中,我从 contenteditable div 中获取文本并循环遍历它们,如果
arr[i]==''
它应该在console.log
return true
但它总是始终返回 false,即使它是一个空字符串(空格)。
If you want to check if a string is empty use:如果要检查字符串是否为空,请使用:
if (!arr[i]) {
// is emtpy
}
Take into consideration that the String is not considered empty if it has whitespace in it!考虑到如果字符串中有空格,则字符串不被视为空! If you want to ignore the whitespace:
如果你想忽略空格:
if (!arr[i].trim()) {
// is empty
}
There is not an empty carácter un this position.在这个位置上没有空字符。 It's a space carácter.
这是一个空间carácter。 You can check if there space characters by using thisfunction.
您可以使用此功能检查是否有空格字符。
function hasWhiteSpace(s) {
return /\s/g.test(s);
}
if(hasWhiteSpace(arr[i]))
{
console.log("i is true"+arr[i]);
}
As A.Wolff pointed out, a space is not an empty string.正如 A.Wolff 指出的那样,空格不是空字符串。 I also changed
==
to ===
to avoid coercion.我也将
==
改为===
以避免强制。 Here's a jsbin这是一个jsbin
js js
function htmltoBBcode() {
$("#hidden").html($('#textEditor').html());
$("#hidden").html($('#textEditor').html());
var arr=$("#hidden").text();
for(var i=0;i<arr.length;i++)
{
if(arr[i]===" ")
{
console.log("i is true: "+arr[i]);
}
else{
console.log("i is false: "+arr[i]);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.