1

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?

5
  • 4
    What you've asked it to match is zero-or-more consecutive characters that are not |. Why not just use myString.split('|') to get an array of strings separated by |? Commented Oct 28, 2015 at 2:00
  • Interesting, any clue why regex101 returns everything instead of just consecutive? That seems odd because it is highly recommended. The .split might work, thanks for the idea. Commented Oct 28, 2015 at 2:06
  • Probably because it doesn't use exec which behaves differently to how you expect it to. See developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Oct 28, 2015 at 2:09
  • regex101 probably uses something more like myString.match(reg) Commented Oct 28, 2015 at 2:11
  • The sad thing is I read the documentation and somehow completely misinterpreted what they were saying. Commented Oct 28, 2015 at 2:17

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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);
}

1 Comment

While exec is a valid way to approach this, match is more convenient in this case.
1

Try a "+" instead of the "*"

So,

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

2 Comments

Doesn't change what exec() returns.
@ActionON it does if you run exec more than once

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.