如何检查SPACE是否存在?跟随名字只能打印第一个单词。
// 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 :(得分:2)
您不需要检查空格。如果有空格,则分割将为您提供名字在数组中第0位的结果,而当空格不存在时,整个名字字符串将在数组中第0位。
var chip_eid = {
"firstname": "RubinRose",
};
if(chip_eid.firstname.includes(" "))
{var res = chip_eid.firstname.split(" ");
member_firstname = res[0];
}
else
member_firstname =chip_eid.firstname ;
console.log(member_firstname);
答案 1 :(得分:1)
尝试使用'/ \ s /'代替'/ ^ * $ /'
var chip_eid = {
"firstname": "Rubin Rose",
};
if (/\s/.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);