Lexone Lexone - 6 months ago 25
Javascript Question

Javascript replace string until a certain point

Basically if I have

var name = "myname yourname";


How can I replace everything with nothing (
""
) in that string until the space character?

So the result would be
name = "yourname";

Answer

Split the string using split(' ') then pop out the last element.

var name = "myname yourname";

console.log(
  name.split(' ').pop()
)


Or using match() or replace() with regex

var name = "myname yourname";

console.log(
  name.match(/\S+$/)[0]
);

// or

console.log(
  name.replace(/^[\s\S]+\s/, '')
);