1

/* How to split the string and store to two variable only name and email id.*/

  var str = "chris <[email protected]>"
  
  /*expected output`enter code here`
  name     = "chris"
  email_id = "[email protected]" */

Must remove the space and the ( "<>" )return the only string.

1
  • You aren't splitting, you're matching. const match = str.match(/(.*)\s*<(.*)>/); then match[1] and match[2] are your name and email. Commented Jan 22, 2021 at 5:31

3 Answers 3

3

you can use regular expression to remove unwanted characters inside a string and assign it to two different variables as below

var str = "chris <[email protected]>"
const [name,email] = str.split(/<|>/g);
Sign up to request clarification or add additional context in comments.

Comments

1

You can use split() the string, replace unwanted values from your string using replace()

var str = "chris <[email protected]>"
var splitedarr=str.split('<');
var name =splitedarr[0];
console.log("name :" + name)
var emailid =splitedarr[1].replace('>','')
console.log("email_id :" +emailid)

Comments

0

I would split the input on the single space occurring after the name and before the email address. Then, take a substring to isolate the email address.

var str = "chris <[email protected]>";
var parts = str.split(/[ ](?=<)/);
var name = parts[0];
var email = parts[1].substring(1, parts[1].length - 1);
console.log("name     = " + name);
console.log("email_id = " + email);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.