I have some function that uses split, but I want the separator to be a variable. separator will be used several places and it would be nice to only have to change the variable once rather than change hard code everywhere.
But, of course, it doesn’t work. The pattern looks correct, but split must have some problem with variables defining the split.
Here is some testing I did in Google Chrome’s console.
separator = '|'; // separator to use
var pattern = '/\\' + separator + '\\s*/'; // define pattern
undefined
pattern;
"/\|\s*/"
// pattern is correct
// now define function with constant... variable version commented:
function split( val ) {
//var pattern = '/\\' + separator + '\\s*/';
return val.split( /\|\s*/ );
//return val.split( pattern );
}
undefined
split('asdf|jkl');
["asdf", "jkl"]
// function worked as expected
// now uncomment the variable portions:
function split( val ) {
var pattern = '/\\' + separator + '\\s*/';
//return val.split( /\|\s*/ );
return val.split( pattern );
}
undefined
split('asdf|jkl');
["asdf|jkl"]
// not as expected. string is not split into array
I assume this has something to do with the split function. How do I get this to work? Note that the only reason I think I need to do it this way is because I want to easily be able to change separator. If not for that, I could just hard code everything it would work.
EDIT:
I don’t care if it uses regex or not. But it needs to split the string on separator and also make sure the values are trimmed of extra spaces.
Also, I’m modeling my code after the jQuery UI page for autocomplete, here.
And here’s the function as they have it. I don’t know why they define their own split.
function split( val ) {
return val.split( /,\s*/ );
}
Concat the string, and use it to create an instance of a new
RegExpobj.EDITS
Note that in this particular example, there doesn’t appear to be any value over String.prototype.split().
This would be more useful if you wanted to set a limit for all splits of a certain type:
without having to write:
Yes, that limit can be stored as a variable and referenced, but then you have to expose that variable throughout the scope of every function you want to use it in.
What if you wanted to change it so it would take an array of strings to split, instead?