简体   繁体   中英

Javascript - How to use variable separator for split function?

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 RegExp obj.

function split( val ) {
        var pattern = new RegExp('\\' + separator + '\\s*'); 
        return val.split( pattern );
}

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:

function split( val ) {
        var pattern = new RegExp('\\' + separator + '\\s*'); 
        return val.split( pattern , 3);
}

without having to write:

strVar.split(pattern, 3);

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?

You can split on a string or on a regular expression, but don't mix them up-

var separator='|', val='Split | on | the | pipes';
val.split(RegExp('\\' + separator + '\\s*')).join('\n');



/*  returned value: (String)
Split 
on 
the 
pipes
*/

Please use split() and don't have a hard time making your own function

http://www.w3schools.com/jsref/jsref_split.asp

A quick example

<p id="demo">Click the button to display the array values after the split.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
var str="How are you doing today?";
var n=str.split(" ");
document.getElementById("demo").innerHTML=n;
}
</script>

then just put the pattern on the split() parameter. make sure escape any character you will put on the parameter because the split() thinks you entered a regex. Your | separator is a regex special character and you must escape it with a backslash

Best way is to just use String.split as it can split by using strings itself.

But as you wish to explore RegEx, you need to ensure the separator is correctly escaped before attempting the split:

Here is a working function where separator can be any string:

function split(val, separator) {
  var separator = separator.replace(/([^\w\s])/g, '\\$1');
  return val.split(new RegExp(separator));
}

split("String|$Array|$Objects", "|$");
> Result ["String", "Array", "Objects"]

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