715 posts
  • Exclusive Author
  • Sold between 100 and 1 000 dollars
  • Belgium
  • Has been a member for 5-6 years
  • Bought between 10 and 49 items
Hy-Studio says

Hello,

I have a string

<p attribute="testAttribute">Some text</p>

I would like to “extract” the attribute value of the paragraph “tag” for further processing. But I don’t know if it’s possible in Javascript to get the value since the content is plain string.

Anyone know how to do this?

Thanks!

484 posts
  • Bought between 10 and 49 items
  • Contributed a Blog Post
  • Contributed a Tutorial to a Tuts+ Site
  • Envato Studio (Microlancer) Beta Tester
  • Exclusive Author
  • Has been a member for 6-7 years
  • Referred between 100 and 199 users
  • Sold between 50 000 and 100 000 dollars
+1 more
omarabid says

If you use jQuery

var str = '<p attribute="testAttribute">Some text</p>';
var my_obj = $(str);
console.info(my_obj.attr('attribute')); // => testAttribute

But don’t use jQuery just to extract the attribute, an alternative is to do it manually (insert the string to the DOM ), and use an identifier for it, but I’m lazy to do that :p

2024 posts
  • Elite Author
  • Author had a Free File of the Month
  • Has been a member for 4-5 years
  • Austria
  • Exclusive Author
  • Interviewed on the Envato Notes blog
  • Envato Studio (Microlancer) Beta Tester
+3 more
revaxarts says

Or with regex:

var str = '<p attribute="testAttribute">Some text</p>';
alert(str.match(/<p attribute="(\w+)">(.*)<\/p>/)[1]);</p>
715 posts
  • Exclusive Author
  • Sold between 100 and 1 000 dollars
  • Belgium
  • Has been a member for 5-6 years
  • Bought between 10 and 49 items
Hy-Studio says

I’m no expert in regular expressions, I find it hard to manage it :/. I’ll try the way that omarabid just proposed.

Thanks!

by
by
by
by
by
by