Javascript 为什么空间没有被检测到,即使有空间?
如何检查是否存在空间?以下名称应仅打印第一个单词Javascript 为什么空间没有被检测到,即使有空间?,javascript,jquery,Javascript,Jquery,如何检查是否存在空间?以下名称应仅打印第一个单词 // var chip_eid = { //"firstname": "Rubin Rose", // }; if (/^ *$/.test(chip_eid.firstname)) { // Find the SPACE? var res = chip_eid.firstname.split(" "); // take Rubin only member_firstname = res[0]; } else { member
// var chip_eid = {
//"firstname": "Rubin Rose",
// };
if (/^ *$/.test(chip_eid.firstname)) { // Find the SPACE?
var res = chip_eid.firstname.split(" "); // take Rubin only
member_firstname = res[0];
}
else {
member_firstname = chip_eid.firstname;
}
console.log(member_firstname); // Printing Rubin Rose instead of Rubin
您不需要检查空格。如果有空格,则拆分将在数组中的第0个位置给出firstname结果,如果没有空格,则整个firstname字符串将在数组中的第0个位置
var-chip\u-eid={
“名字”:“鲁宾罗斯”,
};
if(chip_eid.firstname.includes(“”)
{var res=chip_eid.firstname.split(“”);
成员_firstname=res[0];
}
其他的
成员_firstname=chip_eid.firstname;
console.log(成员名)代码>您不需要检查空格。如果有空格,则拆分将在数组中的第0个位置给出firstname结果,如果没有空格,则整个firstname字符串将在数组中的第0个位置
var-chip\u-eid={
“名字”:“鲁宾罗斯”,
};
if(chip_eid.firstname.includes(“”)
{var res=chip_eid.firstname.split(“”);
成员_firstname=res[0];
}
其他的
成员_firstname=chip_eid.firstname;
console.log(成员名)代码>尝试使用“/\s/”而不是“/^*$/”
var-chip\u-eid={
“名字”:“鲁宾·罗斯”,
};
如果(/\s/.test(chip_eid.firstname)){//找到空格?
var res=chip_eid.firstname.split(“”;//仅取Rubin
成员_firstname=res[0];
}否则{
成员_firstname=chip_eid.firstname;
}
console.log(成员名)代码>尝试使用“/\s/”而不是“/^*$/”
var-chip\u-eid={
“名字”:“鲁宾·罗斯”,
};
如果(/\s/.test(chip_eid.firstname)){//找到空格?
var res=chip_eid.firstname.split(“”;//仅取Rubin
成员_firstname=res[0];
}否则{
成员_firstname=chip_eid.firstname;
}
console.log(成员名)代码>仍然可以不检查就完成。结果是一样的。如果简单地放置Ashay并在空间上拆分它,它将给出整个字符串作为第一个数组元素。无论哪种方式,结果都是一样的。小心像“Rubin Rose”这样的东西,它不再出现在第0个结果中。在这种情况下,regex逻辑或include也会失败。我们必须事先知道firstname属性,才能在ArrayUnderstand中搜索名称,我只是提到它,因为这可能是询问者需要考虑的情况,但您可以不检查就完成。结果是一样的。如果简单地放置Ashay并在空间上拆分它,它将给出整个字符串作为第一个数组元素。无论哪种方式,结果都是一样的。小心像“Rubin Rose”这样的东西,它不再出现在第0个结果中。在这种情况下,regex逻辑或include也会失败。我们必须先知道FrestNess属性来搜索ARARYE中的名字,我只是提一下,因为它可能是ASKER需要考虑的一个案例。