最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use substring() when the string has a space in it - Stack Overflow

programmeradmin3浏览0评论

I have a string containing a person's first and last name such as John Doe. I would like to convert this string to John D. Normally, I would just use substring(0,1) on the last name variable, but how can I achieve this when the first and last name are one string with a space in between?

I have a string containing a person's first and last name such as John Doe. I would like to convert this string to John D. Normally, I would just use substring(0,1) on the last name variable, but how can I achieve this when the first and last name are one string with a space in between?

Share Improve this question edited Jun 14, 2016 at 15:04 Angel Politis 11.3k15 gold badges50 silver badges67 bronze badges asked Jun 14, 2016 at 14:20 Stavros_SStavros_S 2,2357 gold badges36 silver badges80 bronze badges 2
  • What is the expected output for John Frank Doe? Also can you share what have you tried yet? – Rajesh Commented Jun 14, 2016 at 14:21
  • There should never be a middle name but in the case it would be John Frank D. – Stavros_S Commented Jun 14, 2016 at 14:23
Add a comment  | 

8 Answers 8

Reset to default 7

You can do this by splitting the name apart by space and modifying the last name.

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."

This also satisfies the name John Frank Doe as discussed in your question's comments, and will give John Frank D. in that case.

You can use String.split(" "):

str = "John Doe";
strSplit = str.split(" ");
str = strSplit[0] + " " + strSplit[1].substring(0,1);

Note: this only works for cases where it is a first and last name, no middle name.

You can use match for it.

console.log('John Doe'.match(/(.* .)/)[0] +'.');
console.log('John Frank Doe'.match(/(.* .)/)[0] +'.');

You can use string.lastIndexOf()

var fullname = "John Frank Doe";
var result = fullname.substring(0,fullname.lastIndexOf(" ")+2) + ".";
console.log(result)

I recommend using String.replace with regex / (\S)\S*\s*$/:

"John Doe".replace(/ (\S)\S*\s*$/, ' $1.'); // John D.

Examples:

  • John Frank Doe ⇒ John Frank D.
  • Peter P ⇒ Peter P.
  • K ⇒ K
  • Peter O'Neil ⇒ Peter O.
  • Ülfken Österling ⇒ Ülfken Ö.

var names = [
    "John Common",
    "Susan Antony Klein",
    "Elise R. Johann",
    "Simon R. K.",
    "Peter P",
    "Peter",
    "P",
    "Peter O'Neil",
    "Donald McIntyre",
    "John   Whitespace   In   Beween",
    "John Whitespace At The End   ",
    "John Rabe and Rainer Rilke",
    "Ülfken Österling"
  ],
  shorten = name => name.replace(/ (\S)\S*\s*$/, " $1.");

for (name of names) console.log(shorten(name));

For a live regex demo with all test cases, see https://regex101.com/r/zR2nN4/1

For a comparison with the other answers, see https://jsfiddle.net/pwq0bdyz/

Use split() to get last name

var fullName = "John Doe";
var names= fullName .split(" ");
var shortFullName=names[0]+" "+names[1].substring(0,1)+".";
alert(shortFullName);
var a = 'John Doe';
var b = a.split(' ');
var c = b[0] + ' ' + b[1].substring(0,1) + '.'; 

"John D."

you can do that through split to return an array made up of the above string contents separated by spaces then manipulate it through substring:

var name = "first last"; 
var firstLast = name.Split(" "); 
alert(firstLast[0] + " " + firstLast[1].substring(0,1));//
发布评论

评论列表(0)

  1. 暂无评论