1

I have a Javascript array which contains items of string values. However, some of these items contain text in between HTML tags. Below is an example of my array.

var myArr = ["Weather", "very", "<span style="font-weight:bold;">nice</span>"]

How could I strip the <span></span> tags from the array leaving just the word nice?

I have looked into using jquery's .match() to detect if the array contains HTML, but I've no success when testing it in JSFiddle.

Thankyou in advance.

1
  • That's not a valid array ? Commented Feb 15, 2013 at 17:56

2 Answers 2

4

UPDATED

An updated version that prevents against XSS attacks making use of $.parseHTML.

myArr = $.map(myArr, function(str, i){
  return $("<div/>").append($.parseHTML(str)).text();
});

PREVIOUS UPDATE

Probably you can try something along these lines:

myArr = $.map(myArr, function(str, i){
  return $("<div/>").html(str).text();
});

See it here.

Sign up to request clarification or add additional context in comments.

7 Comments

Guess you should use $.map instead of grep.
I was almost sure there was no $.map since Array#map is not yet a viable option. But, agree
There is. =] jQuery.map does exactly what you wanted, while jQuery.grep merely returns a filtered version of the original array. That means, grep evaluates the return value to true/false and then keeps or removes the item from the return value based on that.
Yeah, was just writing up so other readers that are lazy to follow the doc links would see. :P BTW There's a small XSS problem with your code: jsfiddle.net/GTyZe/1 I'd recommend $.parseHTML with the keepScripts param set to false.
@FabrícioMatté, nice catch. It's true that not all readers may not prevent themselves against something like that
|
1
var newArr = [];
var myArr = ["Weather", "very", "<span style=\"font-weight:bold;\">nice</span>"]
$.each(myArr, function(index, value) {
  newArr.push($('<div/>').html(value).text());
});

Working fiddle.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.