1

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?

4
  • myString.split('<strong>') returns the following array: ["", "FirstName LastName</strong>"]. There is no second element, and the first element won't help you produce valid results. Commented Feb 5, 2019 at 0:14
  • You want to take the text in between the tags and use split on that =) Commented Feb 5, 2019 at 0:15
  • Is there a restriction on converting the HTML string to a DOM element and getting .textContent? Commented Feb 5, 2019 at 0:16
  • 2
    what about middlename? Commented Feb 5, 2019 at 3:13

5 Answers 5

5

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' (e.g., 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.

Sign up to request clarification or add additional context in comments.

4 Comments

I'm confused about the createElement part. why do you create a div?
@the_professional_novice Realistically, you can create any element you want, I just used a <div> simply because it seems more sensible.
@the_professional_novice - it might help to think about it better to know that the 2nd line of code is essentially parser.innerHTML = myString; With innerHTML you create a DOM node, then create a <strong> DOM node within that, with whatever your myString value is. One nice thing about this answer is that it works equally well if your myString = <em>First Last</em> or any other decoration around "First Last" (upvoted!)
A div isn't a parser, it calls the built–in parser with possibly unexpected results. I think it would be better to explicitly use a DOM parser: var parser = new DOMParser(); var doc = parser.parseFromString(data, 'text/html'); console.log(doc.body.textContent). :-)
1

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

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

Comments

1

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

1 Comment

@EternalDarkness The comma operator within destructuring assignment omits those indexes.
0

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.

Comments

-1

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);

4 Comments

There is one major caveat to this: it won't work with other strings of different lengths.
Yes, this is not meant to be a catch all but if you know what is in front and back.
It's clear as water that the strings are unknown, of variable length. Why would otherwise OP ask the question in the first place, Icewine...
@Roko C. Buljan I think you need to read the question again. He says: "I have a string that has the following format:..." Then at the end he says "... for any string with that format?" FORMAT he says, not only STRING. In my mind format means "the way in which something is arranged or set out.". Therefore I gave an answer that would strip a string of the starting and ending STRONG and then split the result into an array. It will by the way work for any string that you add in there of any length that starts and ends with strong....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.