3

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');
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. Commented Jan 31, 2012 at 2:19

1 Answer 1

7

You could chain it simply.

var string = document.getElementById('string').value.replace(/\n/g, '<br>').replace('&', '%26');
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - At first I tried your solution, before posting to this forum, however the second replace was only working for the first occurrence of the value. After your suggestion, I also included forward slashes to &, #, and other symbols, and that did the trick - Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.