Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
49
rated 0 times [  52] [ 3]  / answers: 1 / hits: 193600  / 14 Years ago, mon, february 21, 2011, 12:00:00

Is there an easy equivalent to this in JavaScript?



$find = array(<, >, n);
$replace = array(&lt;, &gt;, <br/>);

$textarea = str_replace($find, $replace, $textarea);


This is using PHP's str_replace, which allows you to use an array of words to look for and replace. Can I do something like this using JavaScript / jQuery?



...
var textarea = $(this).val();

// string replace here

$(#output).html(textarea);
...

More From » jquery

 Answers
20

You could extend the String object with your own function that does what you need (useful if there's ever missing functionality):



String.prototype.replaceArray = function(find, replace) {
var replaceString = this;
for (var i = 0; i < find.length; i++) {
replaceString = replaceString.replace(find[i], replace[i]);
}
return replaceString;
};


For global replace you could use regex:



String.prototype.replaceArray = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], g);
replaceString = replaceString.replace(regex, replace[i]);
}
return replaceString;
};


To use the function it'd be similar to your PHP example:



var textarea = $(this).val();
var find = [<, >, n];
var replace = [&lt;, &gt;, <br/>];
textarea = textarea.replaceArray(find, replace);

[#93643] Saturday, February 19, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mckinleyk

Total Points: 730
Total Questions: 99
Total Answers: 99

Location: South Georgia
Member since Fri, Nov 13, 2020
4 Years ago
;