简体   繁体   中英

Regex parsing in javascript

Can you help how to parse the regex i have tried a lot but not able to do.

Input : <a onclick="javascript:collapse('displayText','hideText','whyInfo-arrow-image')"><span sd:text="${whyInfoLabel}">Learn more about Authentication</span> <img id="whyInfo-arrow-image" sd:src="${downwardArrowImage}" height="20" width="20" >

Expected : sd:text="${whyInfoLabel}" and sd:src="${downwardArrowImage}"

My attempt 1 : "/\\$\\{(\\w*)\\}/g" it can pick only {whyInfoLabel} & {downwardArrowImage}

My attempt 2 : "/sd.*\\$\\{(\\w*)\\}/g" this is not able to split.

I am very new to Regex and to JavaScript.

Any help will be great.

You're in JS, why don't you use the DOM to parse HTML instead? Regex isn't designed to parse HTML, but the DOM provides a utility that is designed specifically for that purpose.

If your browser supports it , you should consider doing this using the DOMParser instead:

var html = "<a onclick=\"javascript:collapse('displayText','hideText','whyInfo-arrow-image')\"><span sd:text=\"${whyInfoLabel}\">Learn more about Authentication</span>  <img id=\"whyInfo-arrow-image\" sd:src=\"${downwardArrowImage}\" height=\"20\" width=\"20\" >";

var parser = new DOMParser();
var doc = parser.parseFromString(html, "text/html");

var attrText = doc.querySelector('span').getAttribute("sd:text");
console.log(attrText);

var attrSrc = doc.querySelector('img').getAttribute("sd:src");
console.log(attrSrc);

"${whyInfoLabel}"
"${downwardArrowImage}"

Try this: /(sd:.*=".*")/Ug

Or this: /\\{(.*)\\}/Ug

This should give you both results in an array:

/sd:(?:text|src)=\"[^\"]*"/g

The regex matches 'sd:' at start, followed by 'text' or 'src', a equal sign, a double quote followed by zero or more characters not being a double quote, and finally a double quote.

Just call (assuming your text in a variable called 'text' :

var regex =/sd:(?:text|src)=\"[^\"]*"/g;
var matches = text.match(regex);
var match0 = matches[0];
var match1 = matches[1];

You can try this regex. Hope this helps.

 const regex = /\\w+:\\w+="\\$\\{\\w*\\}"/g; const input = '<a onclick="javascript:collapse(' + 'displayText' + ',' + 'hideText' + ','+ 'whyInfo-arrow-image' + ')"><span sd:text="${whyInfoLabel}">Learn more about Authentication</span> <img id="whyInfo-arrow-image" sd:src="${downwardArrowImage}" height="20" width="20" >'; console.log(input.match(regex))

asdf = new RegExp('(sd:.+?[}])+', 'gi');
console.log(str.match(asdf));

more general:

(?<=["\s])[^\s]+?\s?=\s?"\$\{(?:\w*)\}"

REGEX 101

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM