Get snippet of a String with regular expression in JS

Asked

Viewed 642 times

2

Well, what I need to do is receive a string via input, and "get" a certain value within such a string. Below I show an example to better illustrate the situation:

<iframe width="560" height="315" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.com/maps?layer=c&amp;panoid=goEpsYZX7pQAAAQIt-TW4A&amp;ie=UTF8&amp;source=embed&amp;output=svembed&amp;cbp=13%2C142.07416353827222%2C%2C0%2C-5.103108329005522"></iframe><div><small><a href="https://www.google.com/maps/views/" style="color:#0000FF; text-align:left">Views</a>: <a href="https://www.google.com/maps/views/view/110823397966309387614/gphoto/5911594599652857186" style="color:#0000FF; text-align:left">Wien, Stephanplatz - at the Cathedral church Stephansdom.</a> de <a href="https://www.google.com/maps/views/profile/110823397966309387614" style="color:#0000FF; text-align:left">Bostjan Burger</a></small></div>

The goal here is to rescue the content within the attribute src=. For this I wanted to use javascript, because I will use the onblur event so that when the user "paste" the string I get the src= and move to a <iframe/> display such content.

Starting from the premise that I was able to do this using a regular expression ".*src=\"(.+?)\".*", "$1" using the method replaceAll() how I could do the same in javascript?

I did something, but to no avail:

document.getElementById("yt_input").onblur = function{
    alert("Entrou no metodo...");
    var input = document.getElementById("yt_input").value;
    var expReg = ".*src=\"(.+?)\".*", "$1";
    var resultado = expReg.exec(input);

    alert("Valor do inputSplit:" + resultado[0]);

};

What would be the correct way to obtain such value in order to work with it later?

1 answer

2


First of all, we’re missing one () after function, and that , "$1" on the line that create regex are not valid in Javascript. This corrects the syntax errors.

Second, you need an object RegExp to use regular expressions, string alone is not enough. You can create it from a constructor or a literal:

//var expReg = ".*src=\"(.+?)\".*";
var expReg = new RegExp(".*src=\"(.+?)\".*");
var expReg = /.*src=\"(.+?)\".*/;

Finally, to get the first capture group you must use resultado[1], not zero. Zero gets the complete match (i.e. the whole string).

Complete example in jsFiddle. P.S. It would be nice to also test resultado for null before using it: because it is this result that will occur if the value of input is not in the expected format.

  • Excellent answer... +1!! D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.