ComeRun
ComeRun

Reputation: 921

Regex does not apply to whole string

the following regex

var str = "1234,john smith,jack jone";
var match = str.match(/([^,]*,[^,]*,[^ ]*)/g);
alert(match);

returns

1234,john smith,jack

But what I am trying to get is the whole string which is

1234,john smith,jack jones

Basically my script does the job only for the first whitespace between commas but I want to do it everytime there is a white space between commas.

Can anyone help me out pls.

Upvotes: 2

Views: 93

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 149078

Your pattern excludes spaces from the last section so as soon as it encounters a space in after the third comma, that's the end of the match. You might want to try this instead:

var match = str.match(/[^,]*,[^,]*,.*/g);

This will allow anything after the second comma, including spaces or more commas (since your original pattern allowed commas after the the second).

If you'd like to match pattern only on a single, use start / end anchors (^ / $) as well as the multiline flag (m), like us this:

var match = str.match(/^[^,]*,[^,]*,.*$/mg);

You can try it out with this simple demo.

Upvotes: 4

Damask
Damask

Reputation: 1254

Why you're not using split ?

"1234,john smith,jack jone".split(/,/)

or

"1234,john smith,jack jone".split(",")

Upvotes: 0

Related Questions