javascript 如何使用 jQuery 正则表达式拆分用管道符号分隔的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22558438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:21:39  来源:igfitidea点击:

How can I split a string separated with pipe symbol using jQuery regex

javascriptjqueryregex

提问by Amarnath R Shenoy

I have a dynamically generated string which is basically a row with each value separated by a pipe symbol |, I need to separate it and insert them into a bunch of hidden fields .

我有一个动态生成的字符串,它基本上是一行,每个值用管道符号|分隔,我需要将它分开并将它们插入到一堆隐藏字段中。

This was almost what I needed to do, but not working for me, and I can only use (~or |) as special characters since my data may contain other characters.

这几乎是我需要做的,但对我不起作用,我只能使用 (~|) 作为特殊字符,因为我的数据可能包含其他字符。

Here is my code:

这是我的代码:

var data = "Val1@#|val2$%|val3(*|"; // dynamically generated 

$.each(data.split(/\s*|\s+/), function(i, val) {
    alert(val);
});

回答by fzzle

"Val1@#|val2$%|val3(*|".split('|')works fine. There's no need for regex.
The equivalent with regex would be: .split(/\|/).

"Val1@#|val2$%|val3(*|".split('|')工作正常。不需要正则表达式。
与正则表达式的等效是:.split(/\|/)

回答by Aziz Shaikh

Use this:

用这个:

var Data ="Val1@#|val2$%|val3(*|" //dynamically generated 
alert(Data);
$.each(Data.split(/\|/), function (i, val) {
     alert(val);
})

Working Fiddle: http://jsfiddle.net/nLdcr/

工作小提琴:http: //jsfiddle.net/nLdcr/

回答by fiskeben

No need for regex:

不需要正则表达式:

var list = Data.split("|");

回答by c_buehler

If you are using |for seperating your string, you can use the normal string.split()function of javascript. There is no need to use a regex for this.

如果您|用于分隔字符串,则可以使用string.split()javascript的正常功能。没有必要为此使用正则表达式。

HTML:

HTML:

<div id="result"></div>

Code:

代码:

var data = "Val1@#|val2$%|val3(*|";

$.each(data.split('|'), function(key, value){
    $('#result').append(value).append('<br/>');
});