Created
February 19, 2014 16:40
-
-
Save CrowderSoup/9095873 to your computer and use it in GitHub Desktop.
Replace all instances of a substring without Regex in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var str = 'This is a test string.'; | |
// Let's replace all spaces with ',' | |
str = str.split(' ').join(','); |
Awesome! Works perfectly
Very Clever! 👍
Awesome!
how to replace (t) with (B)
in this example: (this is my Text)
the result is:
Bhis is my TexB
or:
this Is my text
try to replace (is)
???
thanks
Thanks
Awesome, it works around the string length limit with the "replace" method.
INSANE!!!! Thank you for it!
👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
return string.split(' ').reduce(function(prev,curr,index,arr){
curr = curr.replace(/%/,'%25')
.replace(/"/, '%22')
.replace(/</, '%3C')
.replace(/>/,'%3E')
.replace(/#/,'%23')
.replace(/{/,'%7B');
if(index===arr.length-1) return prev+curr;
else return prev+curr+"%20";
},"");
Used this in a recent project.. while you still use regex.. it sort of ensures that all occurences are properly taken care of.