Link to home
Start Free TrialLog in
Avatar of WorknHardr
WorknHardr

asked on

Jquery Split Regex Then Each To Alert Popup?

Hey, working with Jquery and Regex and trying to load a parsed string into an array. So far the Regex works using Expresso. Problem is the Jquery .Split puts a comma between each character anyway. At least the Jqurey .each displays it that way. Unsure if I have a split problem or array write/read problem?

            var words = "my [cell phone] is so [old] its [not cool] anymore"; // Express regex match return

            var arr1 = words.split(new RegExp('\[(\w*\s*)*\]|\w*\s*|\w*'));

            alert(arr1); //m,y, ,[,c,e,l,l, ,p,h,o,n,e,], ,i,s, ,s,o, ,[,o,l,d,], ,i,t,s, ,[,n,o,t, ,c,o,o,l,], ,a,n,y,m,o,r,e

            $.each(arr1, function (index, value) {
                alert(index + ": " + value);  // opens alert over 50 times
            });
Avatar of itnifl
itnifl
Flag of Norway image

Hello. What are you aiming to use this for?
If you access each element in the array and output each element in turn, this will be without the commas. When you access the whole array at once and try to use it as an string, the toString() method is called(except when you use jQuery obviously, see below). This automatically displays the array with each element separated by commas. Don't know if you can override toString() somehow, it wouldn't surprise me. However, it isn't necessary:

Here are some examples - see the link:
http://jsfiddle.net/aL40xbcv/1/

var words = "my [cell phone] is so [old] its [not cool] anymore"; // Express regex match return

var arr1 = words.split(new RegExp('\[(\w*\s*)*\]|\w*\s*|\w*'));

$('#test1').html(arr1.toString());
$('#test2').html(arr1);

$.each(arr1, function (index, value) {
   $('#test3').html($('#test3').html() + " " + index + ": " + value + "<br/>"); 
});

Open in new window

Avatar of WorknHardr
WorknHardr

ASKER

The goal is putting each word into a table using .append(<td><label>'+value+'</td>)
ASKER CERTIFIED SOLUTION
Avatar of itnifl
itnifl
Flag of Norway image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I have a working regex using Expresso editor, but it doesn't work the same in js.split. I maybe confusing split and match, thought I could do both as same time.  This regex / match (Expresso):  

Regex: \[(\w*\s?)*\]|(\w*\s?)
Input: qq [ww] ee pp uu [kk pp] pp [dd gg jj] mm
Output:
qq
[ww]
ee
pp
uu
[kk pp]
pp
[dd gg jj]
mm
thx