Obtain a string with a regular expression in JS

2

Well, what I need to do is get a string via input, and "get" a certain value inside such a string. Below is 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><ahref="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 purpose here is to retrieve the content within the src= attribute. For this I wanted to use javascript, because I will use the onblur event so that when the user "pasts" the string I get the src= and pass to a <iframe/> display such content.

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

I did something, but without success:

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 get this value in order to work on it later?

    
asked by anonymous 03.10.2014 / 00:55

1 answer

2

First, a () is missing after function , and that , "$1" on the line that creates the regex is not valid in JavaScript. This fixes the syntax errors.

Second, you need an object RegExp to use regular expressions, string just 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 catch group you should use resultado[1] , not zero. The zero gets the complete match (i.e. the whole string).

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

03.10.2014 / 01:42