5

How can I get "John" from the string "John Smith"?

(I don't want to use .substring(); because its on a contact form and the value could vary.)

Basically I need to get everything before the first space. ;)

   <h1 id="name">John Smith</h1>

<script>

    var str = document.getElementById("name");

    var first = str.split(" ")[0];

    alert(first);

</script>
1
  • var str = document.getElementById("name").innerHTML
    – sinisake
    Commented Jul 10, 2013 at 3:13

2 Answers 2

9

You can use the String.split method.

"John Smith".split(" ")[0] will return "John"

In your case, it would be:

var str = document.getElementById("name").innerHTML;
var first = str.split(" ")[0];
alert(first);
4
  • Um. I don't see why it wouldn't. I made a JSFiddle to test anyway: jsfiddle.net/SGr9P
    – tekknolagi
    Commented Jul 10, 2013 at 3:11
  • ^ A reference to his previous comment, which suggested that this did not work.
    – tekknolagi
    Commented Jul 10, 2013 at 3:12
  • Hey, Take a look at the code above, what's wrong with it?? Sorry about that previous comment I was referring to the code above, not yours. I deleted it.
    – Matthew
    Commented Jul 10, 2013 at 3:12
  • @MattKnowsTech ah, I see why. Use .innerHTML!
    – tekknolagi
    Commented Jul 10, 2013 at 3:12
4

i dont think the above method is 100% correct

one should use

str.trimStart().split(" ")[0]

it should remove the spaces if present before any characters start.

Not the answer you're looking for? Browse other questions tagged or ask your own question.