Nyxynyx
Nyxynyx

Reputation: 63687

Javascript .match() not working when using /gi flags

When using .match function on a string html, the following code returns an array with the matches.

    html = '<span><b>123</b>C / <b>456</b>K</span>'
    var matches = html.match('<span><b>(.*?)</b>C / <b>(.*?)</b>K</span>')
    console.log(matches)

However after adding the /g flags, the regex no longer returns anything but a null. Is it being used correctly as shown below?

    html = '<span><b>123</b>C / <b>456</b>K</span>'
    var matches = html.match('/<span><b>(.*?)</b>C / <b>(.*?)</b>K</span>/g')
    console.log(matches)

Upvotes: 1

Views: 286

Answers (1)

anubhava
anubhava

Reputation: 785631

Remove quotes from around the regex literal:

var matches = html.match(/<span><b>(.*?)<\/b>C \/ <b>(.*?)<\/b>K<\/span>/i);

When you use '/<span><b>(.*?)</b>C / <b>(.*?)</b>K</span>/gi' then literal string in the quote is used for matching.

Also you need to escape / and remove g to return all the matches.

It will return:

["<span><b>123</b>C / <b>456</b>K</span>", "123", "456"]

Upvotes: 2

Related Questions