Home > Blockchain >  How can i get the url from the string by using regular expression or any javascript method
How can i get the url from the string by using regular expression or any javascript method

Time:12-04

    [
    "<iframe allowFullScreen frameborder=\"0\" height=\"564\" mozallowfullscreen src=\"https://player.vimeo.com/video/253266360\" webkitAllowFullScreen width=\"640\"></iframe>"
]

How can i get the below url from the above ptr string using reg exp: https://player.vimeo.com/video/253266360\ I am trying to split string but not able to get the url.

ptr.split(/(?=:)/)

CodePudding user response:

You can extract a URL from a string using the following RegExp:

/(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\ ~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\ .~#?&//=]*))/

So to get the URL from that string:

const ptr = '<iframe allowFullScreen frameborder="0" height="564" mozallowfullscreen src="https://player.vimeo.com/video/253266360" webkitAllowFullScreen width="640"></iframe>'

const url = /(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\ ~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\ .~#?&//=]*))/.exec(ptr)[0];

When using RegExp.prototype.exec() you, the first element in the returned array is the full string that was matched, in this case https://player.vimeo.com/video/253266360. You can also remove the [0] from the end of the url expression to get the full returned array in case you need other information about the match.

See MDN Docs for more details on the RegExp.exec function.

CodePudding user response:

Perhaps you can leverage the DOM API and do like;

var div = document.createElement("div"),
    src;

div.innerHTML = "<iframe allowFullScreen frameborder=\"0\" height=\"564\" mozallowfullscreen src=\"https://player.vimeo.com/video/253266360\" webkitAllowFullScreen width=\"640\"></iframe>";
src = div.firstChild.src;

console.log(src);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related