× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Segmenting out a full name in JavaScript

Michael Perrenoud
Jun 19, 2015
<p>I would think that <code>split</code> is likely to be the best approach:</p> <pre><code>var segments = currentUser.split(' '); var firstName = segments[0]; var lastName = segments[segments.length - 1]; var middleName = segments.length === 3 ? segments[1] : undefined; </code></pre> <p>Here, <code>firstName</code> and <code>lastName</code> work regardless of the length of the array, or how many segments exist, but the <code>middleName</code> will be set when there are exactly <code>3</code> segments.</p> <p>There is likely another way of doing it with <code>splice</code>; it would probably look something like this:</p> <pre><code>var segments = currentUser.split(' '); var firstName = segments.splice(0, 1)[0]; var middleName = segments.splice(0, 1)[0]; var lastName = segments.splice(0, 1)[0] || middleName; if (middleName === lastName) { middleName = undefined; } alert(firstName + middleName + lastName); </code></pre> <p>I just don't think that's as clean honestly.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/30895264/javascript%20split%20or%20slice?/30895360">Stack Overflow</a>.</p>
comments powered by Disqus