简体   繁体   中英

How to retrieve a word from the string

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.

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;

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());
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM