I need a regex to get the src value of all following strings, considering single, double and no quotes.
With Double Quotes:
var a = '<script class="anyClass" src="anyFile.js" id="anyID">';
var b = '<script class="anyClass" src="anyFile.js">';
var c = '<script src="anyFile.js" id="anyID">';
var d = '<script src="anyFile.js">';
With Single Quotes:
var e = "<script class='anyClass' src='anyFile.js' id='anyID'>";
var f = "<script class='anyClass' src='anyFile.js'>";
var g = "<script src='anyFile.js' id='anyID'>";
var h = "<script src='anyFile.js'>";
Without Quotes:
var i= "<script class=anyClass src=anyFile.js id=anyID>";
var j= "<script class=anyClass src=anyFile.js>";
var k= "<script src=anyFile.js id=anyID>";
var l= "<script src=anyFile.js>";
Expected match/return:
anyFile.js
I have this poor looking solution with split:
var file = "";
var match = 'src="';
if(a.indexOf(match)>=0){
file = a.split(match);
file = file[1];
file = file.split('.js"');
file = file[0] + ".js";
}
else{
match = "src='";
if(a.indexOf(match)>=0){
file = a.split(match);
file = file[1];
file = file.split(".js'");
file = file[0] + ".js";
}
else{
match = "src=";
if(a.indexOf(match)>=0){
file = a.split(match);
file = file[1];
file = file.split('.js');
file = file[0] + ".js";
}
else {
file = "no match";
}
}
}
But it can match wrong src
attributes, so I need a regex.
Any help would be greatly appreciated.
Solution (special thanks to Rajesh)
var a = "<script class='anyClass' src='anyFile.js' id='anyID'>";
var b = '<script class="anyClass" src="anyFile.js">';
var c = '<script src="anyFile.js" id="anyID">';
var d = '<script src="anyFile.js">';
var e = "<script class='anyClass' src='anyFile.js' id='anyID'>";
var f = "<script class='anyClass' src='anyFile.js'>";
var g = "<script src='anyFile.js' id='anyID'>";
var h = "<script src='anyFile.js'>";
var i= "<script class=anyClass src=anyFile.js id=anyID>";
var j= "<script class=anyClass src=anyFile.js>";
var k= "<script src=anyFile.js id=anyID>";
var l= "<script src=anyFile.js>";
var l= "<script src=anyFile.js>";
function getSrc(str){
var regex = /src=["']*[^"' >]+/;
var match = str.match(regex);
if(match!==null){
match = match[0];
var replaceRegex = /src=["' ]*/;
match = match.replace(replaceRegex, "")
}
else{
match = "no match";
}
console.log(match);
}
[a,b,c,d,e,f,g,h,i,j,k,l].forEach(getSrc)