Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple strings at once

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); ... 
like image 862
Tim Avatar asked Feb 21 '11 18:02

Tim


People also ask

How do you replace multiple values in a string?

Show activity on this post. var str = "I have a cat, a dog, and a goat."; str = str. replace(/goat/i, "cat"); // now str = "I have a cat, a dog, and a cat." str = str. replace(/dog/i, "goat"); // now str = "I have a cat, a goat, and a cat." str = str.

How do you replace multiple strings in Excel?

Multiple find and replace in Excel with Substring tool To do mass replace in your worksheet, head over to the Ablebits Data tab and click Substring Tools > Replace Substrings. The Replace Substrings dialog box will appear asking you to define the Source range and Substrings range.

How do you find and replace multiple items in Excel at once?

Use XLOOKUP Function to Search And Replace Multiple Values in Excel. If you're an Excel 365 user then you can go for the XLOOKUP function. The XLOOKUP function searches a range or an array for a match and returns the corresponding item the second range or array.


1 Answers

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); 
like image 51
Bob Avatar answered Sep 22 '22 06:09

Bob