Jump to content


Photo

String replace, caps insensitive... what's a better option?

javascript string replace

Best Answer requinix, 20 December 2013 - 11:21 PM

Use regular expressions:

orig = orig.replace(/&lt;br&gt;/gi, "<br>");
/g is what makes it replace every instance while /i gives you the case insensitivity. Go to the full post


  • Please log in to reply
1 reply to this topic

#1 timneu22

timneu22

    Advanced Member

  • Members
  • PipPipPip
  • 264 posts

Posted 20 December 2013 - 11:03 PM

I just found code that does this:

			orig = orig.replace( "&lt;br&gt;", "<br>" );
			orig = orig.replace( "&lt;BR&gt;", "<br>" );
			orig = orig.replace( "&lt;bR&gt;", "<br>" );
			orig = orig.replace( "&lt;Br&gt;", "<br>" );

I see why it's done this way (to encompass any caps variation on the BR) but since .replace() will only get the first instance, this is just bad all the way around. Also, there's no way to do a toLowerCase() because that will mess up the rest of the string.

 

Is there some sort of JS regex way to replace all instances of &lt;br&gt; regardless of the caps? 

 

Thanks!



#2 requinix

requinix

    Transforming Moderator

  • Moderators
  • 6,124 posts
  • LocationWA

Posted 20 December 2013 - 11:21 PM   Best Answer

Use regular expressions:
orig = orig.replace(/&lt;br&gt;/gi, "<br>");
/g is what makes it replace every instance while /i gives you the case insensitivity.

Edited by requinix, 20 December 2013 - 11:23 PM.





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Cheap Linux VPS from $5
SSD Storage, 30 day Guarantee
1 TB of BW, 100% Network Uptime

AlphaBit.com