简体   繁体   中英

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,

jon.doe@email.com RETURNS Jon Doe
jon_doe@email.com RETURN Jon Doe
jon-doe@email.com 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?

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"]

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/

You can split a string using a regular expression . To match . , _ or - , you can use a character class, for example [.\\-_] . The syntax for regular expressions in JavaScript is /expression/ , so your example would look like:

email.split(/[\.\-_]/);

Note that the backslashes are to prevent . and - being interpreted as special characters. . is a special character class representing any character. In a character class, - can be used to specify ranges, such as [az] .

If you require a dynamic list of characters to split on, you can build a regular expression using the RegExp constructor. For example:

var specialChars = ['.', '\\-', '_'];
var specialRegex = new RegExp('[' + specialChars.join('') + ']');
email.split(specialRegex);

More information on regular expressions in JavaScript can be found on MDN .

You can use regex to do it, just provide a list of the characters in square brackets and escape if necessary.

email.split("[_-\\.]");

Is that what you mean?

Regular Expressions --

email.split(/[_\.-]/)

This one matches (therefore splits at) any of (a character set, indicated by []) _, ., or -.

Here's a good resource for learning regular expressions: http://qntm.org/files/re/re.html

You are correct that you need to use the split function .

Split function works by taking an argument to split the string on. Multiple values can be split via regular expression. For you usage, try something like

var re = /[\._\-]/;
var split = email.split(re, 2);

This should result in an array with two values, first/second name. The second argument is the number of elements returned.

I created a jsFiddle to show how this could be done :

function printName(email){
    var name = email.split('@')[0];
    // source : http://stackoverflow.com/questions/650022/how-do-i-split-a-string-with-multiple-separators-in-javascript
    var returnVal = name.split(/[._-]/g);
    return returnVal;
}

http://jsfiddle.net/ts6nx9tt/1/

If you define your seperators, below code can return all alternatives for you.

var arr = ["_",".","-"];

var email = letters.substr(0, letters.indexOf('@'));
arr.map(function(val,index,rest){
   var r = email.split(val);
   if(r.length > 1){
     return r.join(' ');
   }
   return "";
}
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM