Pick specific characters from a string?

Asked

Viewed 127 times

2

I’m getting the following Javascript string:

Nome Sobrenome <[email protected]>

How do I pick up only the email inside <>??

2 answers

4


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

It would be something like that:

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 the regex:

  • < at the beginning of the part to find
  • ( catch group start marker
  • [^>]+ - anything but > 1 or more times
  • ) catch group end marker
  • > end of part to find in string

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

  • 1

    I’ll try it out and tell you what happened

  • 1

    Sergio, just out of curiosity, would have some way in the regex itself to remove the characters < and > ? I’m trying here and I can’t possibly... x.x

  • It is already being by what I saw running the code above...

  • 1

    @Mathiasfalci yes, but it would be more laborious, in this case it is simpler to exclude <> to include valid characters. But yes, it would be something like this (with reservation for any missing characters): 'Nome Sobrenome <[email protected]>'.match(/[a-z\d_\-.]+@[a-z\d_\-.]+/)[0]

  • 1

    @Sergio Perfeito, thanks for the clarification. @Leonardoebert yes, it is, but for that Sergio took the group of correspondence varianteB[1], I was trying to do this directly in regex.

  • Okay, I get it... it’s just that I don’t understand much about the Regex deal...

  • As for the @Sergio response, it’s just a matter of adapting to the data coming from the server to the client, and I’m going to commit to that now... Thank you again Sergio

  • @Leonardoebert of nothing. I explained more about the regex if it is useful.

  • More knowledge is always useful...

Show 4 more comments

3

Can use regex...

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

I’m going to post because it started @Sergio is very fast

  • I’ll test it to see how it works...

Browser other questions tagged

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