Replace multiple strings with multiple other strings

Specific Solution You can use a function to replace each one. var str = “I have a cat, a dog, and a goat.”; var mapObj = { cat:”dog”, dog:”goat”, goat:”cat” }; str = str.replace(/cat|dog|goat/gi, function(matched){ return mapObj[matched]; }); jsfiddle example Generalizing it If you want to dynamically maintain the regex and just add future exchanges … Read more

How do I replace a character at a particular index in JavaScript?

In JavaScript, strings are immutable, which means the best you can do is to create a new string with the changed content and assign the variable to point to it. You’ll need to define the replaceAt() function yourself: String.prototype.replaceAt = function(index, replacement) { return this.substring(0, index) + replacement + this.substring(index + replacement.length); } And use … Read more

How to replace multiple substrings of a string?

Here is a short example that should do the trick with regular expressions: import re rep = {“condition1”: “”, “condition2”: “text”} # define desired replacements here # use these three lines to do the replacement rep = dict((re.escape(k), v) for k, v in rep.iteritems()) #Python 3 renamed dict.iteritems to dict.items so use rep.items() for latest … Read more

Renaming files by reformatting existing filenames – placeholders in replacement strings used with the -replace operator

Martin Brandl’s answer provides an elegant and effective solution, but it’s worth digging deeper: PowerShell’s -replace operator (… -replace <search>[, <replace>]): Takes a regular expression as its first operand, <search> (the search expression), and invariably matches globally, i.e., it replaces all matches. ‘bar’ -replace ‘[ra]’, ‘@’ -> ‘b@@’ If you want to replace a literal … Read more