Extract inner text from anchor tag string using a regular expression in JavaScript

前端 未结 4 1470
天命终不由人
天命终不由人 2021-01-13 16:38

I am new to angular js . I have regex which gets all the anchor tags. My reg ex is

/]*>([^<]+)<\\/a>/g
         


        
4条回答
  •  日久生厌
    2021-01-13 17:01

    Brief

    Don't use regex for this. Regex is a great tool, don't get me wrong, but it's not what you're looking for. Regex cannot properly parse HTML and should only be used to do so if it's a limited, known set of HTML.

    Try, for example, adding content:">" to your style attribute. You'll see your pattern now fails or gives you an incorrect result. I don't like to use this quote all the time, but I think it's necessary to use it in this case:

    Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

    Use builtin functions. jQuery makes this super easy to accomplish. See my Code section for a demonstration. It's way more legible than any regex variant.


    Code

    DOM from page

    The following snippet gets all anchors on the actual page.

    $("a").each(function() {
      console.log($(this).text())
    })
    
    abc.jagadale@gmail.com
    abc2.jagadale@gmail.com

    DOM in string

    The following snippet gets all anchors in the string (converted to DOM element)

    var s = `email3@domain.com
    email4@domain.com`
    
    $("
    ").html(s).find("a").each(function() { console.log($(this).text()) })
    
    email1@domain.com
    email2@domain.com

提交回复
热议问题