0

I would need to get only the text from certain array. So I need to parse it. I have the following code:

for(var x=0;x<contentArray.length;x++){
markup += '<td>'+contentArray[x+1] +'</td>'; 
x++;
}

Which gives the following output:

<td><c>&lt;ul&gt;&lt;li&gt;The content text&lt;/li&gt;&lt;/ul&gt;</c></td>

And it loks on browser like this:

<ul><li>The content text</li></ul>

Now I would like to get only the text (The content text& in this case). How am I able to do tit?

1
  • 3 quick remarks : why x++ at the end of the for loop? It's already in its condition. Why is there a <c> tag? Can you give us the content of the array or where it comes from? Commented Nov 10, 2010 at 13:48

1 Answer 1

2

You can use this function to unescape HTML (stolen from the Prototype source code):

function unescapeHTML(html) {
    return html
               .replace(/&lt;/g,'<')
               .replace(/&gt;/g,'>')
               .replace(/&amp;/g,'&');
}

You can then use jQuery's parsing capability to get the text from the tags:

for(var x=0;x<contentArray.length;x++){
    var $el = $(unescapeHTML(contentArray[x+1])).find('li'); //use the unescaped HTML to construct a jQuery object and find the li tag within it

    markup += '<td>' + $el.text() + '</td>'; // get the text from the jQuery object and insert it into the fragment
    x++;
}
Sign up to request clarification or add additional context in comments.

5 Comments

This doesnt work. It kills the whole code/app with this. Why is there $ before el? Gives this error: uncaught exception: Syntax error, unrecognized expression: (some text which inside of that ul)
Gives this error in firebug: uncaught exception: Syntax error, unrecognized expression: (The content text)
@sasss If you could provide the contents of contentArray, I might be able to help.
Something like this: <c>Texttext</c>,<c>Texttext</c>,<c>Texttext</c>,<c>&lt;ul&gt;&lt;li&gt;Texttext&lt;/li&gt;&lt;/ul&gt;</c>,<c>Texttext</c>,<c>Texttext</c>,<c>Texttext</c>,<c>Texttext</c>,<c>Pulling action</c>,<c>Texttext</c>,<c>Texttext</c>,<c>Texttext.</c>,<c>Texttext</c>,<c>Texttext</c> The Texttext is obviously something else in real. But text neverthless.
@sasss I've edited my answer. Try now. I'm still not clear exactly what you're trying to do, though. If you could edit your question to give the input and the expected output, that would be great.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.