0

I have a dropdown menu that pulls in text from a database column. The database column can include HTML mark-up. In the drop-down I obviously don't need that in the text. I am working on some jquery and it partially accomplished what I'm looking for. However, it seems to only be replacing the first instance of each character

$('select option').each(function() { 
    this.text = this.text.replace(' ', ' ');
    this.text = this.text.replace('<div>', '' );
    this.text = this.text.replace('</div>', '' );
});

Here is the HTML for the drop-down:

<select name="ctl00$SubPageBody$ClassList" id="ctl00_SubPageBody_ClassList">
<option value="196">Four Week Series: July 19, 2012, 11:00am-12:00pm&<div>July 26, 2012, 11:00am-12:00pm&nbsp;</div><div>August 2, 2012, 11:00am-12:00pm</div><div>August 9, 2012, 11:00am-12:00pm</div></option>

</select>
Jon Harding
  • 4,928
  • 13
  • 51
  • 96

4 Answers4

3

Not sure why there would be HTML within an <option> element to begin with but...

jsFiddle

$('select option').each(function() { 
    this.text = $(this).text();       
});
Gabe
  • 49,577
  • 28
  • 142
  • 181
  • You can see I have that implemented here: http://midwestanxiety.com/TrainingDetails.aspx?ID=59, however it isn't working, any suggestions? – Jon Harding Jun 15 '12 at 15:27
  • Not sure why the above didn't work (works in the jsfiddle), try: `this.text = $(this).html(this.text).text();` – Gabe Jun 15 '12 at 15:39
0

Use regular expressions to replace all instances and do whatever fancy stuff you want:

http://davidwalsh.name/javascript-replace

For example, this will replace 'hello' and/or 'wo':

var s = 'hello world hello';
var s = s.replace(/hello|wo/g, '');

Just keep in mind, you can't parse HTML with regexes :)

RegEx match open tags except XHTML self-contained tags

Community
  • 1
  • 1
Milimetric
  • 13,411
  • 4
  • 44
  • 56
0

I agree that doing this on the server side would be more appropriate.

If you have to do it with Javascript though, you can use regular expressions:

$(this).text().replace(/REPLACEME/g, 'repclacement');

Mind the g at the end of the RegEx: it's the global flag.

You will also need to escape some special characters like /. So would be </div>.

theduke
  • 3,027
  • 4
  • 29
  • 28
0

You can use the /g option in regex to replace all instances on a line.

this.text = this.text.replace(/<\/div>/g, '' );

Notice that / replaces ' when you want to find with regex.

middleinitial
  • 649
  • 3
  • 10