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

2020/10/13 20:01 · javascript ·  · 0评论

我正在尝试用多个其他单词替换字符串中的多个单词。字符串是“我有一只猫,一只狗和一只山羊”。

但是,它不会产生“我有一只狗,一只山羊和一只猫”,而是会产生“我有一只猫,一只猫和一只猫”。在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".

具体解决方案

您可以使用一个函数替换每个函数。

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示例

概括它

如果您想动态维护正则表达式并仅将将来的交换添加到地图,则可以执行此操作

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

生成正则表达式。所以它看起来像这样

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

要添加或更改更多替换,您只需编辑地图即可。 

摆弄动态正则表达式

使其可重用

如果您希望将其作为通用模式,则可以将其拉出类似这样的函数

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

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

因此,您只需将str和要替换的内容的映射传递给函数,它将返回转换后的字符串。

摆弄功能

为了确保Object.keys在较旧的浏览器中可以正常工作,请添加一个polyfill例如从MDNEs5

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

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

您将按以下方式调用它:

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

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

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

然后

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

工作原理:-%\ d +查找%之后的数字。方括号捕获数字。

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

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

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

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

在现代JavaScript中:-

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

这对我有用:

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"

以防万一有人想知道为什么原始海报的解决方案不起作用:

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

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


// /////////////    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

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

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

用户常规函数定义要替换的模式,然后使用替换函数对输入字符串进行处理,

var i = new RegExp('"{','g'),
    j = new RegExp('}"','g'),
    k = data.replace(i,'{').replace(j,'}');
    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."

您可以使用定界符查找和替换字符串。

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;
}
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方法用于字符串,它根据需要使用多个参数,并将所有参数替换为我们指定的最后一个参数2013 CopyRights保存为: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/

<!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>

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

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

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

"this is a test string for stringInject"

或者您可以将占位符替换为对象键和值,如下所示:

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

"My username is tjcafferkey on Github" 

为此,您可以使用https://www.npmjs.com/package/union-replacer从本质string.replace(regexp, ...)上讲,它是一种对等方,它允许一次替换进行多次替换,同时保留的全部功能string.replace(...)

披露:我是作者。该库是为了支持更复杂的用户可配置替换而开发的,它解决了所有问题,例如捕获组,后向引用和回调函数替换。

上面的解决方案足以精确替换字符串。

通过使用原型函数,我们可以轻松地通过将键,值和可替换文本传递给对象来进行替换

String.prototype.replaceAll=function(obj,keydata='key'){
 const keys=keydata.split('key');
 return Object.entries(obj).reduce((a,[key,val])=> a.replace(`${keys[0]}${key}${keys[1]}`,val),this)
}

const data='hids dv sdc sd ${yathin} ${ok}'
console.log(data.replaceAll({yathin:12,ok:'hi'},'${key}'))

所有解决方案都可以很好地工作,除非应用于闭包的编程语言(例如,Coda,Excel,Spreadsheet REGEXREPLACE)。

下面的我的两个原始解决方案仅使用1个级联和1个正则表达式。

方法1:查找替换值

想法是如果替换值不在字符串中,则附加它们。然后,使用单个正则表达式执行所有需要的替换:

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;

说明:

  • cat(?=[\s\S]*(dog))表示我们在寻找“猫”。如果匹配,则正向查找将捕获“ dog”作为组1,否则捕获“”。
  • 与将“山羊”捕获为组2的“狗”和将“猫”捕获为组3的“山羊”相同。
  • 我们将替换为"$1$2$3"(所有三个组的并置),对于上述情况之一,它始终为“狗”,“猫”或“山羊”
  • 如果我们手动将替换内容附加到like之类的字符串上str+"||||cat,dog,goat",我们也会通过匹配将其删除\|\|\|\|.*$,在这种情况下,替换项"$1$2$3"将求值为空字符串“”。

方法2:查找替换对

方法1的一个问题是,一次不能超过9个替换,这是反向传播组的最大数量。方法2声明不只是附加替换值,而是直接替换:

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;

说明:

  • (str+"||||,cat=>dog,dog=>goat,goat=>cat") 这就是我们将替换映射附加到字符串末尾的方式。
  • (\b\w+\b) 声明“捕获任何单词”,可以用“(cat | dog | goat)或其他任何内容替换”。
  • (?=[\s\S]*...) 是一个前向查询,通常会一直到文档末尾,直到替换映射之后。

    • ,\1=> 表示“您应该在逗号和右箭头之间找到匹配的词”
    • ([^,]*) 表示“匹配此箭头后的所有内容,直到下一个逗号或文档的末尾”
  • |\|\|\|\|.*$ 是如何删除替换图。

我在@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)

返回“等等……234433等等……”

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

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));
    });
});
本文地址:http://javascript.askforanswer.com/yongduogeqitazifuchuantihuanduogezifuchuan.html
文章标签: ,   ,   ,   ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!