Reputation: 341
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
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
.
substr(starting pos, end pos)
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
Reputation: 37606
Simply use substr
and indexOf
:
var name = name.substr(name.indexOf(' ') + 1) ;
Upvotes: 4