Search code examples
jqueryhref

jQuery if string contains a link return link value


Using regex to check if the string has a link

<p>Random text <a href="/landing.html">click here</a></p>
<p>Another paragraph without href</p>

and if true return the string and use str.find("a").attr("href"); to get the href value.

var str = $('p').html();
if(new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?").test(str)) {
    console.log(str);
    var href = str.find("a").attr("href");
}

However, console.log returns error

Uncaught TypeError: str.find is not a function

Check Link Jsfiddle in advance


Solution

  • The issue with above code is you are using .html() method because html returns the html part not the dom object. You need to use the dom selector object to find the anchor. Update your code to below

    var str = $('p');
    console.log(str)
    if(new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?").test(str.html())) {
        console.log(str);
        var href = str.find("a").attr("href");
      console.log(href)
    }
    

    Check the fiddle updated fiddle