Javascript regex match fails on actual page, but regex tests work just fine

前端 未结 1 843
心在旅途
心在旅途 2020-11-28 16:46

I have a very specific problem concerning a regular expression matching in Javascript. I\'m trying to match a piece of source code, more specifically a portion here:

相关标签:
1条回答
  • 2020-11-28 17:31

    You're putting your regular expression inside a string. It should not be inside a string.

    var world = document.documentElement.innerHTML.match(/boardid=[0-9]+">([A-Z][a-z]+)( - Trade){0,1}<\/a>/i)[1];
    

    Another thing — it appears you have a document object, in which case all this HTML is already parsed for you, and you can take advantage of that instead of reinventing a fragile wheel.

    var element = document.querySelector('a[href*="boardid="]');
    var world = element.textContent;
    

    (This assumes that you don't need <=IE8 support. If you do, there remains a better way, though.)

    (P.S. ? is shorthand for {0,1}.)

    0 讨论(0)
提交回复
热议问题