用多个其他字符串替换多个字符串

时间:2022-12-10 07:53:40

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 have a dog, a goat, and a cat", but instead it produces "I have a cat, a cat, and a cat". Is it possible to replace multiple strings with multiple other strings at the same time in JavaScript, so that the correct result will be produced?

然而,这并不能产生“我养了一只狗、一只山羊和一只猫”,但它却产生了“我养了一只猫、一只猫和一只猫”。在JavaScript中,是否可以同时用多个其他字符串替换多个字符串,从而产生正确的结果?

var str = "I have a cat, a dog, and a goat.";
str = str.replace(/cat/gi, "dog");
str = str.replace(/dog/gi, "goat");
str = str.replace(/goat/gi, "cat");

//this produces "I have a cat, a cat, and a cat"
//but I wanted to produce the string "I have a dog, a goat, and a cat".

12 个解决方案

#1


280  

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

jsfiddle例子

Generalizing it

If you want to dynamically maintain the regex and just add future exchanges to the map, you can do this

如果您想动态维护regex并向映射添加未来的交换,您可以这样做

new RegExp(Object.keys(mapObj).join("|"),"gi"); 

to generate the regex. So then it would look like this

生成正则表达式。它是这样的

var mapObj = {cat:"dog",dog:"goat",goat:"cat"};

var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
str = str.replace(re, function(matched){
  return mapObj[matched];
});

And to add or change any more replacements you could just edit the map. 

要添加或更改任何替换,只需编辑映射。

fiddle with dynamic regex

摆弄动态正则表达式

Making it Reusable

If you want this to be a general pattern you could pull this out to a function like this

如果你想让它成为一个通用模式你可以把它变成这样的函数

function replaceAll(str,mapObj){
    var re = new RegExp(Object.keys(mapObj).join("|"),"gi");

    return str.replace(re, function(matched){
        return mapObj[matched.toLowerCase()];
    });
}

So then you could just pass the str and a map of the replacements you want to the function and it would return the transformed string.

然后你可以把这个str和替换的映射传递给这个函数它会返回转换后的字符串。

fiddle with function

摆弄函数

To ensure Object.keys works in older browsers, add a polyfill eg from MDN or Es5.

确保对象。键在旧的浏览器中工作,添加来自MDN或Es5的polyfill eg。

#2


5  

This may not meet your exact need in this instance, but I've found this a useful way to replace multiple parameters in strings, as a general solution. It will replace all instances of the parameters, no matter how many times they are referenced:

这可能不能满足您在此实例中的确切需求,但我发现这是一种替换字符串中的多个参数的有用方法,作为通用解决方案。它将替换所有参数的实例,无论它们被引用多少次:

String.prototype.fmt = function (hash) {
        var string = this, key; for (key in hash) string = string.replace(new RegExp('\\{' + key + '\\}', 'gm'), hash[key]); return string
}

You would invoke it as follows:

你将按以下方式调用它:

var person = '{title} {first} {last}'.fmt({ title: 'Agent', first: 'Jack', last: 'Bauer' });
// person = 'Agent Jack Bauer'

#3


3  

This worked for me:

这工作对我来说:

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};

function replaceAll(str, map){
    for(key in map){
        str = str.replaceAll(key, map[key]);
    }
    return str;
}

//testing...
var str = "bat, ball, cat";
var map = {
    'bat' : 'foo',
    'ball' : 'boo',
    'cat' : 'bar'
};
var new = replaceAll(str, map);
//result: "foo, boo, bar"

#4


2  

user regular function to define the pattern to replace and then use replace function to work on input string,

用户正则函数定义要替换的模式,然后使用替换函数来处理输入字符串,

var i = new RegExp('"{','g'),
    j = new RegExp('}"','g'),
    k = data.replace(i,'{').replace(j,'}');

#5


0  

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:

/* replaceSome method for strings它用很多参数替换所有参数用我们指定的2013版权保存的最后一个参数Max Ahmed这是一个例子:

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/

jsFiddle:http://jsfiddle.net/CPj89/

#6


0  

<!DOCTYPE html>
<html>
<body>



<p id="demo">Mr Blue 
has a           blue house and a blue car.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var str = document.getElementById("demo").innerHTML;
    var res = str.replace(/\n| |car/gi, function myFunction(x){

if(x=='\n'){return x='<br>';}
if(x==' '){return x='&nbsp';}
if(x=='car'){return x='BMW'}
else{return x;}//must need



});

    document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>

#7


0  

Just in case someone is wondering why the original poster's solution is not working:

以防有人想知道为什么最初的海报解决方案行不通:

var str = "I have a cat, a dog, and a goat.";

str = str.replace(/cat/gi, "dog");
// now str = "I have a dog, a dog, and a goat."

str = str.replace(/dog/gi, "goat");
// now str = "I have a goat, a goat, and a goat."

str = str.replace(/goat/gi, "cat");
// now str = "I have a cat, a cat, and a cat."

#8


0  

I wrote this npm package stringinject https://www.npmjs.com/package/stringinject which allows you to do the following

我编写了这个npm包stringinject https://www.npmjs.com/package/stringinject,它允许您执行以下操作

var string = stringInject("this is a {0} string for {1}", ["test", "stringInject"]);

which will replace the {0} and {1} with the array items and return the following string

它将用数组项替换{0}和{1},并返回以下字符串?

"this is a test string for stringInject"

or you could replace placeholders with object keys and values like so:

或者可以用对象键和值替换占位符,比如:

var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });

"My username is tjcafferkey on Github" 

#9


0  

Using Jquery Replace multiple strings with multiple other strings

使用Jquery将多个字符串替换为多个其他字符串

     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));
});
});

#10


0  

With my replace-once package, you could do the following:

使用我的replace-once包,您可以做以下事情:

const replaceOnce = require('replace-once')

var str = 'I have a cat, a dog, and a goat.'
var find = ['cat', 'dog', 'goat']
var replace = ['dog', 'goat', 'cat']
replaceOnce(str, find, replace, 'gi')
//=> 'I have a dog, a goat, and a cat.'

#11


0  

Use numbered items to prevent replacing again. eg

使用编号的项目,以防止再次更换。如

let str = "I have a %1, a %2, and a %3";
let pets = ["dog","cat", "goat"];

then

然后

str.replace(/%(\d+)/g, (_, n) => pets[+n-1])

#12


-1  

I expanded on @BenMcCormicks a bit. His worked for regular strings but not if I had escaped characters or wildcards. Here's what I did

我稍微扩展了一下@BenMcCormicks。他使用的是常规字符串,但如果我使用了转义字符或通配符,就不能使用。这是我所做的

str = "[curl] 6: blah blah 234433 blah blah";
mapObj = {'\\[curl] *': '', '\\d: *': ''};


function replaceAll (str, mapObj) {

    var arr = Object.keys(mapObj),
        re;

    $.each(arr, function (key, value) {
        re = new RegExp(value, "g");
        str = str.replace(re, function (matched) {
            return mapObj[value];
        });
    });

    return str;

}
replaceAll(str, mapObj)

returns "blah blah 234433 blah blah"

返回"blah 234433 blah blah"

This way it will match the key in the mapObj and not the matched word'

这样它将匹配mapObj中的键而不是匹配的单词'

#1


280  

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

jsfiddle例子

Generalizing it

If you want to dynamically maintain the regex and just add future exchanges to the map, you can do this

如果您想动态维护regex并向映射添加未来的交换,您可以这样做

new RegExp(Object.keys(mapObj).join("|"),"gi"); 

to generate the regex. So then it would look like this

生成正则表达式。它是这样的

var mapObj = {cat:"dog",dog:"goat",goat:"cat"};

var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
str = str.replace(re, function(matched){
  return mapObj[matched];
});

And to add or change any more replacements you could just edit the map. 

要添加或更改任何替换,只需编辑映射。

fiddle with dynamic regex

摆弄动态正则表达式

Making it Reusable

If you want this to be a general pattern you could pull this out to a function like this

如果你想让它成为一个通用模式你可以把它变成这样的函数

function replaceAll(str,mapObj){
    var re = new RegExp(Object.keys(mapObj).join("|"),"gi");

    return str.replace(re, function(matched){
        return mapObj[matched.toLowerCase()];
    });
}

So then you could just pass the str and a map of the replacements you want to the function and it would return the transformed string.

然后你可以把这个str和替换的映射传递给这个函数它会返回转换后的字符串。

fiddle with function

摆弄函数

To ensure Object.keys works in older browsers, add a polyfill eg from MDN or Es5.

确保对象。键在旧的浏览器中工作,添加来自MDN或Es5的polyfill eg。

#2


5  

This may not meet your exact need in this instance, but I've found this a useful way to replace multiple parameters in strings, as a general solution. It will replace all instances of the parameters, no matter how many times they are referenced:

这可能不能满足您在此实例中的确切需求,但我发现这是一种替换字符串中的多个参数的有用方法,作为通用解决方案。它将替换所有参数的实例,无论它们被引用多少次:

String.prototype.fmt = function (hash) {
        var string = this, key; for (key in hash) string = string.replace(new RegExp('\\{' + key + '\\}', 'gm'), hash[key]); return string
}

You would invoke it as follows:

你将按以下方式调用它:

var person = '{title} {first} {last}'.fmt({ title: 'Agent', first: 'Jack', last: 'Bauer' });
// person = 'Agent Jack Bauer'

#3


3  

This worked for me:

这工作对我来说:

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};

function replaceAll(str, map){
    for(key in map){
        str = str.replaceAll(key, map[key]);
    }
    return str;
}

//testing...
var str = "bat, ball, cat";
var map = {
    'bat' : 'foo',
    'ball' : 'boo',
    'cat' : 'bar'
};
var new = replaceAll(str, map);
//result: "foo, boo, bar"

#4


2  

user regular function to define the pattern to replace and then use replace function to work on input string,

用户正则函数定义要替换的模式,然后使用替换函数来处理输入字符串,

var i = new RegExp('"{','g'),
    j = new RegExp('}"','g'),
    k = data.replace(i,'{').replace(j,'}');

#5


0  

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:

/* replaceSome method for strings它用很多参数替换所有参数用我们指定的2013版权保存的最后一个参数Max Ahmed这是一个例子:

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/

jsFiddle:http://jsfiddle.net/CPj89/

#6


0  

<!DOCTYPE html>
<html>
<body>



<p id="demo">Mr Blue 
has a           blue house and a blue car.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var str = document.getElementById("demo").innerHTML;
    var res = str.replace(/\n| |car/gi, function myFunction(x){

if(x=='\n'){return x='<br>';}
if(x==' '){return x='&nbsp';}
if(x=='car'){return x='BMW'}
else{return x;}//must need



});

    document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>

#7


0  

Just in case someone is wondering why the original poster's solution is not working:

以防有人想知道为什么最初的海报解决方案行不通:

var str = "I have a cat, a dog, and a goat.";

str = str.replace(/cat/gi, "dog");
// now str = "I have a dog, a dog, and a goat."

str = str.replace(/dog/gi, "goat");
// now str = "I have a goat, a goat, and a goat."

str = str.replace(/goat/gi, "cat");
// now str = "I have a cat, a cat, and a cat."

#8


0  

I wrote this npm package stringinject https://www.npmjs.com/package/stringinject which allows you to do the following

我编写了这个npm包stringinject https://www.npmjs.com/package/stringinject,它允许您执行以下操作

var string = stringInject("this is a {0} string for {1}", ["test", "stringInject"]);

which will replace the {0} and {1} with the array items and return the following string

它将用数组项替换{0}和{1},并返回以下字符串?

"this is a test string for stringInject"

or you could replace placeholders with object keys and values like so:

或者可以用对象键和值替换占位符,比如:

var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });

"My username is tjcafferkey on Github" 

#9


0  

Using Jquery Replace multiple strings with multiple other strings

使用Jquery将多个字符串替换为多个其他字符串

     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));
});
});

#10


0  

With my replace-once package, you could do the following:

使用我的replace-once包,您可以做以下事情:

const replaceOnce = require('replace-once')

var str = 'I have a cat, a dog, and a goat.'
var find = ['cat', 'dog', 'goat']
var replace = ['dog', 'goat', 'cat']
replaceOnce(str, find, replace, 'gi')
//=> 'I have a dog, a goat, and a cat.'

#11


0  

Use numbered items to prevent replacing again. eg

使用编号的项目,以防止再次更换。如

let str = "I have a %1, a %2, and a %3";
let pets = ["dog","cat", "goat"];

then

然后

str.replace(/%(\d+)/g, (_, n) => pets[+n-1])

#12


-1  

I expanded on @BenMcCormicks a bit. His worked for regular strings but not if I had escaped characters or wildcards. Here's what I did

我稍微扩展了一下@BenMcCormicks。他使用的是常规字符串,但如果我使用了转义字符或通配符,就不能使用。这是我所做的

str = "[curl] 6: blah blah 234433 blah blah";
mapObj = {'\\[curl] *': '', '\\d: *': ''};


function replaceAll (str, mapObj) {

    var arr = Object.keys(mapObj),
        re;

    $.each(arr, function (key, value) {
        re = new RegExp(value, "g");
        str = str.replace(re, function (matched) {
            return mapObj[value];
        });
    });

    return str;

}
replaceAll(str, mapObj)

returns "blah blah 234433 blah blah"

返回"blah 234433 blah blah"

This way it will match the key in the mapObj and not the matched word'

这样它将匹配mapObj中的键而不是匹配的单词'