-1

This is my HTML string<img class='left' alt='&quot;&quot;' src='182-35622' title='MyImage_147x91.png' uri='182-35622' style='width: 147px; height: 91px;'> How to get the "title" value from regular expression using javascript only.

I want output should be "MyImage_147x91.png"

any suggestions?

i tried so far it's not working

 var htmlString = "<img class='left' alt='&quot;&quot;' src='182-35622' title='MyImage_147x91.png' uri='182-35622' style='width: 147px; height: 91px;'>"

 var setCookieMetaRegExp = /<img title=[\"'](.*)[\"'].*>/ig;

 var matches = [];

while (setCookieMetaRegExp.exec(htmlString)) {
  //matches.push(RegExp.$1);
}
NorthStar
  • 1
  • 1
  • [Don't use regex to parse html.](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – Karl Reid Jun 07 '17 at 21:00
  • Possible duplicate of [Regular expression for extracting tag attributes](https://stackoverflow.com/questions/317053/regular-expression-for-extracting-tag-attributes) –  Jun 07 '17 at 21:00
  • There are so many questions already on this exact topic. –  Jun 07 '17 at 21:01
  • Are you sure you can't just get the node and do `node.title`? – Karl Reid Jun 07 '17 at 21:02

3 Answers3

1

Why not use HTML DOM information to obtain image title?

var img = document.querySelector('img.left');
console.log(img.title);
<img class='left' alt='&quot;&quot;' src='182-35622' title='MyImage_147x91.png' uri='182-35622' style='width: 147px; height: 91px;'>

If you really need to use regex on the string try below:

var s = "<img class='left' alt='&quot;&quot;' src='182-35622' title='MyImage_147x91.png' uri='182-35622' style='width: 147px; height: 91px;'>";
var regex = /title\s*=\s*'([^']*)/;
console.log(regex.exec(s)[1]);

Regex DEMO with explanation

MaxZoom
  • 7,619
  • 5
  • 28
  • 44
0

You should avoid using regular expressions to parse HTML. Instead, use the getAttribute method:

const img = document.querySelector('.left');
img.getAttribute('title'); // => MyImage_147x91.png
ughitsaaron
  • 517
  • 4
  • 10
0

You could use something like this.

title='([^']+)'

Use this website to learn regex. Though based on the other answers to this question there are better ways to go about doing this.

Benjamin Commet
  • 350
  • 3
  • 8