当字符串中有空格时,如何使用substring()

Sta*_*s_S 3 javascript

我有一个字符串,其中包含一个人的名字和姓氏,例如John Doe.我想将此字符串转换为John D.常规,我只会使用substring(0,1)姓氏变量,但如果名字和姓氏是一个字符串,并且介于两者之间,我怎么能实现这一点?

小智 7

你可以使用String.split(""):

str = "John Doe";
strSplit = str.split(" ");
str = strSplit[0] + " " + strSplit[1].substring(0,1);
Run Code Online (Sandbox Code Playgroud)

注意:这仅适用于名字和姓氏,没有中间名称的情况.


Jam*_*ger 6

您可以通过将名称除以空格并修改姓氏来实现此目的.

var name = "John Doe"; // store the name

var nameParts = name.split(" "); // split the name by spaces

var lastName = nameParts[nameParts.length - 1]; // get the last name
lastName = lastName.substring(0, 1) + "."; // replace the last name with the first letter and a full stop

nameParts[nameParts.length - 1] = lastName; // insert the last name back into the array of names at the end

name = nameParts.join(" "); // join the names back together with their original spaces

console.log(name); // gives "John D."
Run Code Online (Sandbox Code Playgroud)

这也满足John Frank Doe您的问题评论中讨论的名称,并将John Frank D.在这种情况下给出.

  • 当姓氏是麦当劳或麦当劳或奥尼尔时呢? (2认同)