简体   繁体   English

Javascript - 如何使用变量分隔符进行拆分功能?

[英]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. 我有一些使用split的函数,但我希望separator是一个变量。 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. separator将被用于几个地方,只需更改变量一次而不是在任何地方更改硬代码将是很好的。

But, of course, it doesn't work. 但是,当然,它不起作用。 The pattern looks correct, but split must have some problem with variables defining the split. 该模式看起来正确,但split必须对定义拆分的变量有一些问题。

Here is some testing I did in Google Chrome's console. 以下是我在Google Chrome控制台中进行的一些测试。

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. 我认为这与split函数有关。 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 . 请注意,我认为我需要这样做的唯一原因是因为我希望能够轻松地更改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. 但它需要在separator上拆分字符串,并确保修剪额外空格的值。

Also, I'm modeling my code after the jQuery UI page for autocomplete, here . 此外,我在自动完成的jQuery UI页面之后为我的代码建模, 在这里 And here's the function as they have it. 这是他们拥有的功能。 I don't know why they define their own split . 我不知道为什么他们定义自己的split

function split( val ) {
     return val.split( /,\s*/ );
}

Concat the string, and use it to create an instance of a new RegExp obj. Concat该字符串,并使用它来创建一个新的RegExp obj的实例。

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

EDITS EDITS

Note that in this particular example, there doesn't appear to be any value over String.prototype.split(). 请注意,在此特定示例中,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 请使用split()并且没有时间制作自己的功能

http://www.w3schools.com/jsref/jsref_split.asp 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. 然后只需将模式放在split()参数上。 make sure escape any character you will put on the parameter because the split() thinks you entered a regex. 确保转义将放在参数上的任何字符,因为split()认为你输入了一个正则表达式。 Your | 你的| separator is a regex special character and you must escape it with a backslash separator是一个正则表达式特殊字符,你必须用反斜杠转义它

Best way is to just use String.split as it can split by using strings itself. 最好的方法是使用String.split,因为它可以通过使用字符串本身进行拆分。

But as you wish to explore RegEx, you need to ensure the separator is correctly escaped before attempting the split: 但是,如果您希望探索RegEx,则需要确保在尝试拆分之前正确转义分隔符:

Here is a working function where separator can be any string: 这是一个工作函数,其中separator可以是任何字符串:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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