Matthew
Matthew

Reputation: 2246

Get some string before the space, and save it in a variable with Javascript

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>

Upvotes: 5

Views: 10997

Answers (2)

Sami Ullah
Sami Ullah

Reputation: 877

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.

Upvotes: 4

tekknolagi
tekknolagi

Reputation: 11012

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

Upvotes: 10

Related Questions