简体   繁体   中英

JavaScript get first name and last name from string as array

I have a string that has the following format: <strong>FirstName LastName</strong> How can I change this into an array with the first element firstName and second lastName?

I did this, but no luck, it won't produce the right result:

var data = [myString.split('<strong>')[1], myString.split('<strong>')[2]]

How can I produce ["firstName", "lastName"] for any string with that format?

In order to parse HTML, use the best HTML parser out there, the DOM itself!

 // create a random element, it doesn't have to be 'strong' (eg, it could be 'div') var parser = document.createElement('strong'); // set the innerHTML to your string parser.innerHTML = "<strong>FirstName LastName</strong>"; // get the text inside the element ("FirstName LastName") var fullName = parser.textContent; // split it into an array, separated by the space in between FirstName and LastName var data = fullName.split(" "); // voila! console.log(data); 

EDIT

As @RobG pointed out, you could also explicitly use a DOM parser rather than that of an element:

 var parser = new DOMParser(); var doc = parser.parseFromString("<strong>FirstName LastName</strong>", "text/html"); console.log(doc.body.textContent.split(" ")); 

However, both methods work perfectly fine; it all comes down to preference.

Just match everything between <strong> and </strong> .

 var matches = "<strong>FirstName LastName</strong>".match(/<strong>(.*)<\\/strong>/); console.log(matches[1].split(' ')); 

The preferred approach would be to use DOM methods; create an element and get the .textContent then match one or more word characters or split space character.

 let str = '<strong>FirstName LastName</strong>'; let [,first, last] = str.split(/<[/\\w\\s-]+>|\\s/g); console.log(first, last); 

/<[/\w\s-]+>|\s/g

Splits < followed by one or more word, space or dash characters characters followed by > character or space to match space between words in the string.

Comma operator , within destructuring assignment is used to omit that index from the result of .split() ["", "FirstName", "LastName", ""] .

this is my approach of doing your problem. Hope it helps!

var str = "<strong>FirstName LastName</strong>";
var result = str.slice(0, -9).substr(8).split(" ");

Edit: it will only work for this specific example.

Another way to do this in case you had something other than an html

 var string = "<strong>FirstName LastName</strong>"; string = string.slice(0, -9); // remove last 9 chars string = string.substr(8); // remove first 8 chars string = string.split(" "); // split into an array at space console.log(string); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM