Replace all after first blank

2

I have a variable that can store compound words, as in the example below. I would like help with the replace() method in order to replace everything after the 1st (first) whitespace , regardless of content and length. So the value of the variable phr would be "moved up", and would be "stirred", eliminating everything from the first (blank) ie "up" would be eliminated in the given example. It is important that the deletion be performed using the replace() method, as the substitution criterion must be the 1st (first) whitespace . Thanks in advance for your attention.

var phr = 'stirred up';
    
asked by anonymous 15.03.2015 / 04:03

2 answers

4

You can use a regular expression in replace :

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

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

    
15.03.2015 / 04:11
1

Another way to do it, without having to use regular expressions, is this:

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

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

    
15.03.2015 / 08:54