0

I have a string of the following form:

data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'>Avatar data

It can be in different languages, but in any case I need to get a string which is between the characters ' ' That is, in the example above, I need to get the following string:

view-7631b26ea80b1b601c313b15cc4e2ab03faedf30

Can I do this using the method string.replace(regexp, str) ?

I've highlighted the desired line using the following regular expression:

/'\b(.*)\b'/gm

Now, using the method string.replace I need to delete everything except that...

Got any suggestions?

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Ivan Kuzyshyn
  • 165
  • 1
  • 1
  • 7
  • 1
    It looks a lot like you're trying to use a regular expression to successfully extract data from HTML. [That's usually doomed to fail](http://stackoverflow.com/a/1732454/157247). 80% solutions are pretty easy, but the 20% will get you. – T.J. Crowder Oct 16 '15 at 08:13

3 Answers3

0

Use match method.

var data = "data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'>Avatar data";
data = data.match(/'\b(.*)\b'/gm)
Gilsha
  • 14,431
  • 3
  • 32
  • 47
0

You have good solid anchor text in either side, so:

var match = /data-translate='([^']+)'/.exec(str);
var substr = match && match[1];

Live Example:

var str = "data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'>Avatar data";
var match = /data-translate='([^']+)'/.exec(str);
var substr = match && match[1];
document.body.innerHTML =
  "<pre>Got: [" + substr + "]</pre>";

But again, as I said in a comment, using a simple regular expression to extract information from HTML is usually doomed to fail. For instance, you probably don't want to match this:

<p>The string is data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'</p>

...and yet, a simple regex solution will do exactly that. To properly handle HTML, you must use a proper HTML parser.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

You can also try this one:

/\'([^\']+)\'/gm
Mayur Koshti
  • 1,794
  • 15
  • 20