Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
});
like image 968
Amarnath R Shenoy Avatar asked Mar 21 '14 12:03

Amarnath R Shenoy


People also ask

How do I split a string with multiple separators in JQuery?

Use the String. split() method to split a string with multiple separators, e.g. str. split(/[-_]+/) . The split method can be passed a regular expression containing multiple characters to split the string with multiple separators.

How do you do a split symbol?

split well-known symbol specifies the method that splits a string at the indices that match a regular expression. This function is called by the String. prototype. split() method.

How use split with regex in JS?

To split a string by a regular expression, pass a regex as a parameter to the split() method, e.g. str. split(/[,. \s]/) . The split method takes a string or regular expression and splits the string based on the provided separator, into an array of substrings.


1 Answers

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/

like image 170
Aziz Shaikh Avatar answered Sep 30 '22 11:09

Aziz Shaikh