Replace all after first white space

Asked

Viewed 469 times

2

I have a variable that can store compound words, as in the example below. I would like help with the method replace() in order to replace all after the 1st (first) white space, does not matter its content and length. So the variable value phr would be "Stirred up", and would be "Stirred", eliminating everything from the 1st (first) white space, i.e., "up" would be deleted in the given example. It is important that the elimination is performed through the method replace(), for the substitution criterion shall be the 1st (first) blank. Thanks for your attention.

var phr = 'stirred up';

2 answers

4


You can use a regular expression in the replace:

var phr = 'stirred up';
phr = phr.replace(/\s.*/, '')
// phr agora = "stirred"

The \s takes the first space and .* takes all the remaining characters from the string.

  • Thank you very much André. Exactly what I wanted. Your reply was very helpful.

  • @If this answer served you, accept it to mark the problem as solved.

1

Another way to do it, without using regular expressions, is the following:

var antes = 'stirred up';
var depois = antes.split(' ')[0];
alert("Antes: " + antes + "; Depois: " + depois);

This then splits the string into several pieces using the spaces as separators ('stirred up' will turn ['stirred', 'up']) and then the [0] takes the first element of the string.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.