Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript splitting a string at special character

I am trying to "intelligently" pre-fill a form, I want to prefill the firstname and lastname inputs based on a user email address, so for example,

[email protected] RETURNS Jon Doe
[email protected] RETURN Jon Doe
[email protected] RETURNS Jon Doe

I have managed to get the string before the @,

var email = letters.substr(0, letters.indexOf('@'));

But cant work out how to split() when the separator can be multiple values, I can do this,

email.split("_")

but how can I split on other email address valid special characters?

like image 252
Cycs Avatar asked Aug 12 '14 14:08

Cycs


2 Answers

JavaScript's string split method can take a regex.

For example the following will split on ., -, and _.

"i-am_john.doe".split(/[.\-_]/)

Returning the following.

["i", "am", "john", "doe"]
like image 163
Alexander O'Mara Avatar answered Oct 20 '22 17:10

Alexander O'Mara


You can use a regular expression for what you want to split on. You can for example split on anything that isn't a letter:

var parts = email.split(/[^A-Za-z]/);

Demo: http://jsfiddle.net/Guffa/xt3Lb9e6/

like image 37
Guffa Avatar answered Oct 20 '22 19:10

Guffa