ActionON
ActionON

Reputation: 106

Regex: .exec() function not returning expected output

This doesn't return what I, or regex101, expects:

var myString = "Accel World|http://www.anime-planet.com/anime/accel-worldAh! My Goddess|http://www.anime-planet.com/anime/ah-my-goddess";
var reg = /[^|]*/g;
var regResponse = reg.exec(myString);
console.log(regResponse);

according to regex101, this should match everything except '|' and return it yet it only matches the first string, Accel World, as opposed to everything but '|'.

How do I fix this?

Upvotes: 1

Views: 478

Answers (3)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196142

Exec will only return one result at a time (subsequent calls will return the rest, but you also need to use the + instead of *)

You could use the myString.match(reg) htough to get all results in one go.

var myString = "Accel World|http://www.anime-planet.com/anime/accel-worldAh! My Goddess|http://www.anime-planet.com/anime/ah-my-goddess";
var reg = /[^|]+/g;
var regResponse = myString.match(reg);
console.log(regResponse);

Upvotes: 3

Griffith
Griffith

Reputation: 3217

You need to loop .exec() to retrieve all matches. The documentation says

If your regular expression uses the "g" flag, you can use the exec() method multiple times to find successive matches in the same string.

var reg = /[^|]+/g;
while(regResponse = reg.exec(myString)) {
    console.log(regResponse);
}

Upvotes: 1

shaunxer
shaunxer

Reputation: 52

Try a "+" instead of the "*"

So,

var reg = /[^|]+/g;

Upvotes: 1

Related Questions