Scott Thornton
Scott Thornton

Reputation: 341

Strip Characters after space in Javascript

I need to strip out the characters that are before a space in javascript. See code below:

var name = "First Last";

How can I strip out "First" and just leave "Last".

Also, Will I get the same results if the var was the below? or would it just output "Last" still? Is there a way to just strip upto the first space?

var name = "First Middle Last";

Thanks.

Upvotes: 0

Views: 70

Answers (3)

Mouser
Mouser

Reputation: 13304

name = "First middle last";
var name = name.substr(name.indexOf(" ")+1);

document.body.innerHTML += name;

Will get the part after the first space.

You will need to things for this: substr and indexOf.

  • The first takes part of a string substr(starting pos, end pos)
  • The second calculates the position of the first occurrence of the variable. The +1 is needed or else the space would be included.

Upvotes: 0

ᔕᖺᘎᕊ
ᔕᖺᘎᕊ

Reputation: 3011

Regex: (.*?)\s

Explanation:

1st Capturing group (.*?)
.*? matches any character (except newline)
Quantifier: *? Between zero and unlimited times, as few times as possible, expanding as needed [lazy]
\s match any white space character [\r\n\t\f ]

newStr = "First Middle Last".replace(/(.*?)\s/, "");
console.log(newStr);

Upvotes: 2

Holt
Holt

Reputation: 37606

Simply use substr and indexOf:

var name = name.substr(name.indexOf(' ') + 1) ;

Upvotes: 4

Related Questions