I\'m trying to replace multiple words in a string with multiple other words. The string is \"I have a cat, a dog, and a goat.\"
However, this does not produce \"I ha
using Array.prototype.reduce():
const arrayOfObjects = [
{ plants: 'men' },
{ smart:'dumb' },
{ peace: 'war' }
]
const sentence = 'plants are smart'
arrayOfObjects.reduce(
(f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence
)
// as a reusable function
const replaceManyStr = (obj, sentence) => obj.reduce((f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence)
const result = replaceManyStr(arrayOfObjects , sentence1)
Example
// ///////////// 1. replacing using reduce and objects
// arrayOfObjects.reduce((f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence)
// replaces the key in object with its value if found in the sentence
// doesn't break if words aren't found
// Example
const arrayOfObjects = [
{ plants: 'men' },
{ smart:'dumb' },
{ peace: 'war' }
]
const sentence1 = 'plants are smart'
const result1 = arrayOfObjects.reduce((f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence1)
console.log(result1)
// result1:
// men are dumb
// Extra: string insertion python style with an array of words and indexes
// usage
// arrayOfWords.reduce((f, s, i) => `${f}`.replace(`{${i}}`, s), sentence)
// where arrayOfWords has words you want to insert in sentence
// Example
// replaces as many words in the sentence as are defined in the arrayOfWords
// use python type {0}, {1} etc notation
// five to replace
const sentence2 = '{0} is {1} and {2} are {3} every {5}'
// but four in array? doesn't break
const words2 = ['man','dumb','plants','smart']
// what happens ?
const result2 = words2.reduce((f, s, i) => `${f}`.replace(`{${i}}`, s), sentence2)
console.log(result2)
// result2:
// man is dumb and plants are smart every {5}
// replaces as many words as are defined in the array
// three to replace
const sentence3 = '{0} is {1} and {2}'
// but five in array
const words3 = ['man','dumb','plant','smart']
// what happens ? doesn't break
const result3 = words3.reduce((f, s, i) => `${f}`.replace(`{${i}}`, s), sentence3)
console.log(result3)
// result3:
// man is dumb and plants
String.prototype.replaceSome = function() {
var replaceWith = Array.prototype.pop.apply(arguments),
i = 0,
r = this,
l = arguments.length;
for (;i<l;i++) {
r = r.replace(arguments[i],replaceWith);
}
return r;
}
/* replaceSome method for strings it takes as ,much arguments as we want and replaces all of them with the last argument we specified 2013 CopyRights saved for: Max Ahmed this is an example:
var string = "[hello i want to 'replace x' with eat]";
var replaced = string.replaceSome("]","[","'replace x' with","");
document.write(string + "<br>" + replaced); // returns hello i want to eat (without brackets)
*/
jsFiddle: http://jsfiddle.net/CPj89/
All solutions work great, except when applied in programming languages that closures (e.g. Coda, Excel, Spreadsheet's REGEXREPLACE
).
Two original solutions of mine below use only 1 concatenation and 1 regex.
The idea is to append replacement values if they are not already in the string. Then, using a single regex, we perform all needed replacements:
var str = "I have a cat, a dog, and a goat.";
str = (str+"||||cat,dog,goat").replace(
/cat(?=[\s\S]*(dog))|dog(?=[\s\S]*(goat))|goat(?=[\s\S]*(cat))|\|\|\|\|.*$/gi, "$1$2$3");
document.body.innerHTML = str;
Explanations:
cat(?=[\s\S]*(dog))
means that we look for "cat". If it matches, then a forward lookup will capture "dog" as group 1, and "" otherwise."$1$2$3"
(the concatenation of all three groups), which will always be either "dog", "cat" or "goat" for one of the above casesstr+"||||cat,dog,goat"
, we remove them by also matching \|\|\|\|.*$
, in which case the replacement "$1$2$3"
will evaluate to "", the empty string.One problem with Method #1 is that it cannot exceed 9 replacements at a time, which is the maximum number of back-propagation groups. Method #2 states not to append just replacement values, but replacements directly:
var str = "I have a cat, a dog, and a goat.";
str = (str+"||||,cat=>dog,dog=>goat,goat=>cat").replace(
/(\b\w+\b)(?=[\s\S]*,\1=>([^,]*))|\|\|\|\|.*$/gi, "$2");
document.body.innerHTML = str;
Explanations:
(str+"||||,cat=>dog,dog=>goat,goat=>cat")
is how we append a replacement map to the end of the string.(\b\w+\b)
states to "capture any word", that could be replaced by "(cat|dog|goat) or anything else.(?=[\s\S]*...)
is a forward lookup that will typically go to the end of the document until after the replacement map.
,\1=>
means "you should find the matched word between a comma and a right arrow"([^,]*)
means "match anything after this arrow until the next comma or the end of the doc"|\|\|\|\|.*$
is how we remove the replacement map. 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.replace(/cat/i, "dog");
// now str = "I have a dog, a goat, and a cat."
You can find and replace string using delimiters.
var obj = {
'firstname': 'John',
'lastname': 'Doe'
}
var text = "My firstname is {firstname} and my lastname is {lastname}"
alert(mutliStringReplace(obj,text))
function mutliStringReplace(object, string) {
var val = string
var entries = Object.entries(object);
entries.forEach((para)=> {
var find = '{' + para[0] + '}'
var regExp = new RegExp(find,'g')
val = val.replace(regExp, para[1])
})
return val;
}
Solution with Jquery (first include this file): Replace multiple strings with multiple other strings:
var replacetext = {
"abc": "123",
"def": "456"
"ghi": "789"
};
$.each(replacetext, function(txtorig, txtnew) {
$(".eng-to-urd").each(function() {
$(this).text($(this).text().replace(txtorig, txtnew));
});
});