substring/regex to get a src value held in a string

前端 未结 7 1116
花落未央
花落未央 2021-01-02 05:25

I have a string with the value:

var string = \"\'\'
Some plain text
7条回答
  •  感情败类
    2021-01-02 06:02

    One approach, is the following:

    var string = "
    Some plain text
    http://www.google.com", srcWithQuotes = string.match(/src\=([^\s]*)\s/)[1], src = srcWithQuotes.substring(1,srcWithQuotes.length - 1); console.log(src);​

    JS Fiddle demo.

    This effectively matches a sequence of characters starting with src= (the = is escaped with a back-slash because, otherwise, it holds special meaning within regular expressions), followed by a sequence of non-white-space characters (^\s*) followed by a white-space character (\s).

    This expression explicitly captures the quotes used to delimit the src attribute, the src is returned by taking a substring of the srcWithQuotes variable, starting at 1 (the first, the zeroeth, character should be the attribute delimiter) until the index before the last character (the final quote delimiting the attribute).

    There is a slightly convoluted (but potentially more reliable) approach, using a document fragment:

    var string = "
    Some plain text
    http://www.google.com", temp = document.createElement('div'), frag = document.createDocumentFragment(); temp.innerHTML = string; frag.appendChild(temp); console.log(temp.getElementsByTagName('img')[0].src);​​​​​​

    JS Fiddle demo.

    Of course, in this example, you could use any approach you like to find the image within the temp node (getElementById(), getElementsByClassName()...).

提交回复
热议问题