node.js 用多个其他字符串替换多个字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15604140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 13:59:53  来源:igfitidea点击:

Replace multiple strings with multiple other strings

javascriptnode.jsregexstringreplace

提问by Anderson Green

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".

回答by Ben McCormick

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

如果您想动态维护正则表达式并仅将未来的交换添加到地图中,您可以这样做

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 MDNor Es5.

为了确保 Object.keys 在旧浏览器中工作,添加一个polyfill,例如来自MDNEs5

回答by Iian

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: 'Hyman', last: 'Bauer' });
// person = 'Agent Hyman Bauer'

回答by Quentin 2

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])

How it works:- %\d+ finds the numbers which come after a %. The brackets capture the number.

它是如何工作的:- %\d+ 查找 % 之后的数字。括号捕获数字。

This number (as a string) is the 2nd parameter, n, to the lambda function.

这个数字(作为字符串)是 lambda 函数的第二个参数 n。

The +n-1 converts the string to the number then 1 is subtracted to index the pets array.

+n-1 将字符串转换为数字,然后减去 1 以索引 pets 数组。

The %number is then replaced with the string at the array index.

然后将 %number 替换为数组索引处的字符串。

The /g causes the lambda function to be called repeatedly with each number which is then replaced with a string from the array.

/g 导致对每个数字重复调用 lambda 函数,然后将其替换为数组中的字符串。

In modern JavaScript:-

在现代 JavaScript 中:-

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

回答by Jo?o Paulo

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"

回答by Emmanuel N K

using Array.prototype.reduce():

使用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

回答by Hyman

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."

回答by Naresh Kumar

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}"

console.log(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;
}

回答by Anand Kumar Singh

    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."

回答by Kodie Grantham

With my replace-oncepackage, you could do the following:

使用我的替换一次包,您可以执行以下操作:

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.'

回答by KARTHIKEYAN.A

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