Reputation: 517
str = <a href = "#homecoupon" class ="current">COUPONS</a>
how to get the word COUPONS from the str. the word #homecoupon might change to other word so i can't do the substring method of retrieving the nth position value. the class ="current">COUPONS</a>
will always be fixed.
Is there a way i can back track and retrieve the last nth word.
Upvotes: 0
Views: 123
Reputation: 219938
The best way to parse HTML in the browser is to let the browser do it for you.
Create a dummy element in memory, then set its innerHTML
to your string. You can then use the regular DOM API to find the text of that anchor element:
var div = document.createElement('div');
div.innerHTML = str;
var word = div.firstChild.textContent;
Here's the fiddle: http://jsfiddle.net/mREFu/
If you still have to support IE < 9, you'll have to use this:
var word = div.firstChild.textContent || div.firstChild.innerText;
Or you could get the text from the text node:
var word = div.firstChild.childNodes[0].nodeValue;
Upvotes: 5
Reputation: 7187
Using substring()
and indexof()
you can do this.
str = '<a href = "#homecoupon" class ="current">COUPONS</a>';
// get rid of </a> assuming the string always ends with it
var x = str.substring(0,str.length-4);
// use the fixed part to get the value you want
alert(x.substring(x.indexOf('class ="current">')+17))
OR
str = '<a href = "#homecoupon" class ="current">COUPONS</a>';
fixedPart = 'class ="current">';
// use the fixed part to get the value you want assuming str always ends with </a>
alert(str.substring(str.indexOf(fixedPart)+fixedPart.length, str.length-4))
Upvotes: 0
Reputation: 99234
If it's an actual string not a part of a web page :
var str = '<a href = "#homecoupon" class ="current">COUPONS</a>';
var word = str.match(/"current">(.*?)</);
if(word) word = word[1]; //== COUPONS
Or if you're using jQuery and that's an actual web page you can go :
$('a.current').each(function(){
alert($(this).text());
});
Upvotes: 0