Akshay
Akshay

Reputation: 177

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.

Upvotes: 0

Views: 614

Answers (6)

user47589
user47589

Reputation:

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}"

Upvotes: 1

Andre Elrico
Andre Elrico

Reputation: 11500

more general:

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

REGEX 101

Upvotes: 0

Sven Liivak
Sven Liivak

Reputation: 1413

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

Upvotes: 0

Alex G
Alex G

Reputation: 1917

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))

Upvotes: 0

Poul Bak
Poul Bak

Reputation: 10940

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];

Upvotes: 0

rib
rib

Reputation: 92

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

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

Upvotes: 0

Related Questions