Picking specific characters from a string?

2

I'm getting the following String in Javascript:

Nome Sobrenome <[email protected]>

How do I get only the email that is within <> ??

    
asked by anonymous 31.08.2017 / 16:12

2 answers

4

You can use a regex for this, or String.slice .

It would look something like this:

var string = 'Nome Sobrenome <[email protected]>';


var varianteA = string.slice(
  string.indexOf('<') + 1,
  string.indexOf('>')
);
console.log(varianteA);

var varianteB = string.match(/<([^>]+)>/);
varianteB = varianteB ? varianteB[1] : '';
console.log(varianteB);

About regex:

  • < at the beginning of the part to be found
  • % with% capture group start marker
  • ( - all but [^>]+ 1 or more times
  • % with% catcher endpoint marker
  • > end of part to be found in string

Then I used ) if there is no > and avoid errors before trying to access varianteB = varianteB ? varianteB[1] : ''; if the match gives match .

    
31.08.2017 / 16:17
3

You can use regex ...

 alert("<[email protected]>".match(/\<([^)]+)\>/)[1]);

I'll post it because it already started @Sergio is very fast

    
31.08.2017 / 16:19