I am trying to replace multiple values in a string with JS replace(). The values that I want to replace include line breaks, &, #, etc... I know how to replace one value:
var string = document.getElementById('string').value.replace(\/n/g, '<br>');
However, what is the syntax to include other values. For example, how can I make the below replace functions one function?
var string = document.getElementById('string').value.replace(\/n/g, '<br>')
var string = document.getElementById('string').value.replace('&', '%26');
I am trying to replace multiple values in a string with JS replace(). The values that I want to replace include line breaks, &, #, etc... I know how to replace one value:
var string = document.getElementById('string').value.replace(\/n/g, '<br>');
However, what is the syntax to include other values. For example, how can I make the below replace functions one function?
var string = document.getElementById('string').value.replace(\/n/g, '<br>')
var string = document.getElementById('string').value.replace('&', '%26');
Share
Improve this question
asked Jan 31, 2012 at 1:40
user175328user175328
3233 gold badges10 silver badges23 bronze badges
1
-
You could create an object of strings and replacements:
{ '&': '%26, ' ': '%20', ... }
and then loop through to do the replacements, but I think @xdazz's answer is probably just as good or better. – glortho Commented Jan 31, 2012 at 2:19
1 Answer
Reset to default 7You could chain it simply.
var string = document.getElementById('string').value.replace(/\n/g, '<br>').replace('&', '%26');