How do I loop through a regex's matches inside a replace in javascript?

I have the following JavaScript (the spaces in the `

`s are non-breaking): var html = '...

  • sub 2
  • \n\

    i. subsub 1

    \n\

    ii. subsub 2

    \n\
      \n\
        \n\
      1. sub 3
      ...'; $(function () { var nestedListFixer = /(?:<\/li><\/ol>\s*)+(?:

      (?:&(?:nbsp|\#0*160|x0*A0);)+(?:\s[ivxlcdm]+\.)(?:&(?:nbsp|\#0*160|x0*A0);)+\s(.*?)<\/p>\s*)+(?:\s*)+/i; html = html.replace(nestedListFixer, function($0, $1){ var lis = "" $.each($1, function () { lis += "

    1. " + this + "
    2. \n"; }); alert("
        \n" + lis + "
      "); return "
        \n" + lis + "
      "; }); }); The `alert()`'s output:
      1. s
      2. u
      3. b
      4. s
      5. u
      6. b
      7. 2
      Here's what I hoped it would be:
      1. subsub 1
      2. subsub 2
      How do I correctly loop through each match in the `$1`? **Update:** simplified pattern and matching example: var text = '1ab2cb3cd4ab5cb6cd7'; $(function () { var textFixer = /(?:a)(?:b(.*?)c)+(?:d)/i; text = text.replace(textFixer, function($0, $1){ var numbers = ""; $.each($1, function () { numbers += this; }); alert(numbers); return numbers; }); alert(text); }); // actual text: // 13467 // desired text: // 1234567
      Can you not simplify your code, regex, and markup so people can more easily understand your problem and therefore help you more? (Not a rhetorical question)

    以上就是How do I loop through a regex's matches inside a replace in javascript?的详细内容,更多请关注web前端其它相关文章!

    赞(0) 打赏
    未经允许不得转载:web前端首页 » JavaScript 答疑

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址

    前端开发相关广告投放 更专业 更精准

    联系我们

    觉得文章有用就打赏一下文章作者

    支付宝扫一扫打赏

    微信扫一扫打赏