Javascript 一次替换多个字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5069464/
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-08-23 15:31:00  来源:igfitidea点击:

Replace multiple strings at once

javascriptjqueryreplace

提问by Tim

Is there an easy equivalent to this in JavaScript?

在 JavaScript 中有一个简单的等价物吗?

$find = array("<", ">", "\n");
$replace = array("&lt;", "&gt;", "<br/>");

$textarea = str_replace($find, $replace, $textarea); 

This is using PHP's str_replace, which allows you to use an array of words to look for and replace. Can I do something like this using JavaScript / jQuery?

这是使用 PHP 的str_replace,它允许您使用一组单词来查找和替换。我可以使用 JavaScript / jQuery 做这样的事情吗?

...
var textarea = $(this).val();

// string replace here

$("#output").html(textarea);
...

回答by Bob

You could extend the String object with your own function that does what you need (useful if there's ever missing functionality):

您可以使用自己的函数扩展 String 对象,该函数可以满足您的需要(如果缺少功能,则很有用):

String.prototype.replaceArray = function(find, replace) {
  var replaceString = this;
  for (var i = 0; i < find.length; i++) {
    replaceString = replaceString.replace(find[i], replace[i]);
  }
  return replaceString;
};

For global replace you could use regex:

对于全局替换,您可以使用正则表达式:

String.prototype.replaceArray = function(find, replace) {
  var replaceString = this;
  var regex; 
  for (var i = 0; i < find.length; i++) {
    regex = new RegExp(find[i], "g");
    replaceString = replaceString.replace(regex, replace[i]);
  }
  return replaceString;
};

To use the function it'd be similar to your PHP example:

要使用该函数,它类似于您的 PHP 示例:

var textarea = $(this).val();
var find = ["<", ">", "\n"];
var replace = ["&lt;", "&gt;", "<br/>"];
textarea = textarea.replaceArray(find, replace);

回答by Stephen M. Harris

Common Mistake

常见的错误

Nearly all answers on this page use cumulative replacement and thus suffer the same flaw where replacement strings are themselves subject to replacement. Here are a couple examples where this pattern fails (h/t @KurokiKaze @derekdreery):

此页面上的几乎所有答案都使用累积替换,因此存在替换字符串本身需要替换的相同缺陷。以下是此模式失败的几个示例(h/t @KurokiKaze @derekdreery):

function replaceCumulative(str, find, replace) {
  for (var i = 0; i < find.length; i++)
    str = str.replace(new RegExp(find[i],"g"), replace[i]);
  return str;
};

// Fails in some cases:
console.log( replaceCumulative( "tar pit", ['tar','pit'], ['capitol','house'] ) );
console.log( replaceCumulative( "you & me", ['you','me'], ['me','you'] ) );

Solution

解决方案

function replaceBulk( str, findArray, replaceArray ){
  var i, regex = [], map = {}; 
  for( i=0; i<findArray.length; i++ ){ 
    regex.push( findArray[i].replace(/([-[\]{}()*+?.\^$|#,])/g,'\') );
    map[findArray[i]] = replaceArray[i]; 
  }
  regex = regex.join('|');
  str = str.replace( new RegExp( regex, 'g' ), function(matched){
    return map[matched];
  });
  return str;
}

// Test:
console.log( replaceBulk( "tar pit", ['tar','pit'], ['capitol','house'] ) );
console.log( replaceBulk( "you & me", ['you','me'], ['me','you'] ) );

Note:

笔记:

This is a more compatible variation of @elchininet's solution, which uses map()and Array.indexOf()and thus won't work in IE8 and older.

这是@ elchininet的更加兼容的变化的解决方案,它使用map()Array.indexOf(),因而不会在IE8工作和老年人。

@elchininet's implementation holds truer to PHP's str_replace(), because it also allows strings as find/replace parameters, and will use the first find array match if there are duplicates (my version will use the last). I didn't accept strings in this implementation because that case is already handled by JS's built-in String.replace().

@elchininet 的实现更符合 PHP 的str_replace(),因为它也允许字符串作为查找/替换参数,并且如果有重复项将使用第一个查找数组匹配(我的版本将使用最后一个)。我在这个实现中没有接受字符串,因为这种情况已经由 JS 的内置String.replace().

回答by hsz

text = text.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br/>');

回答by ElChiniNet

You could use the replace method of the Stringobject with a function in the second parameter:

您可以将String对象的 replace 方法与第二个参数中的函数一起使用:

First Method (using a find and replace Object)

第一种方法(使用查找和替换对象)

var findreplace = {"<" : "&lt;", ">" : "&gt;", "\n" : "<br/>"};

textarea = textarea.replace(new RegExp("(" + Object.keys(findreplace).map(function(i){return i.replace(/[.?*+^$[\]\(){}|-]/g, "\$&")}).join("|") + ")", "g"), function(s){ return findreplace[s]});

jsfiddle

提琴手

Second method (using two arrays, find and replace)

第二种方法(使用两个数组,查找和替换)

var find = ["<", ">", "\n"];
var replace = ["&lt;", "&gt;", "<br/>"];

textarea = textarea.replace(new RegExp("(" + find.map(function(i){return i.replace(/[.?*+^$[\]\(){}|-]/g, "\$&")}).join("|") + ")", "g"), function(s){ return replace[find.indexOf(s)]});

jsfiddle

提琴手

Desired function:

所需功能:

function str_replace($f, $r, $s){
   return $s.replace(new RegExp("(" + $f.map(function(i){return i.replace(/[.?*+^$[\]\(){}|-]/g, "\$&")}).join("|") + ")", "g"), function(s){ return $r[$f.indexOf(s)]});
}

$textarea = str_replace($find, $replace, $textarea);

EDIT

编辑

This functionadmits a Stringor an Arrayas parameters:

function承认 aString或 anArray作为参数:

function str_replace($f, $r, $s){
    return $s.replace(new RegExp("(" + (typeof($f) === "string" ? $f.replace(/[.?*+^$[\]\(){}|-]/g, "\$&") : $f.map(function(i){return i.replace(/[.?*+^$[\]\(){}|-]/g, "\$&")}).join("|")) + ")", "g"), typeof($r) === "string" ? $r : typeof($f) === "string" ? $r[0] : function(i){ return $r[$f.indexOf(i)]});
}

回答by Utopik

A more visual approach:

更直观的方法:

String.prototype.htmlProtect = function() {
  var replace_map;

  replace_map = {
    '\n': '<br />',
    '<': '&lt;',
    '>': '&gt;'
  };

  return this.replace(/[<>\n]/g, function(match) { // be sure to add every char in the pattern
    return replace_map[match];
  });
};

and this is how you call it:

这就是你的称呼:

var myString = "<b>tell me a story, \n<i>bro'</i>";
var myNewString = myString.htmlProtect();

// &lt;b&gt;tell me a story, <br />&lt;i&gt;bro'&lt;/i&gt;

回答by user1925159

String.prototype.replaceArray = function (find, replace) {
    var replaceString = this;
    for (var i = 0; i < find.length; i++) {
        // global replacement
        var pos = replaceString.indexOf(find[i]);
        while (pos > -1) {
            replaceString = replaceString.replace(find[i], replace[i]);
            pos = replaceString.indexOf(find[i]);
        }
    }
    return replaceString;
};

var textT = "Hello world,,,,, hello people.....";
var find = [".",","];
var replace = ['2', '5'];
textT = textT.replaceArray(find, replace);
// result: Hello world55555 hello people22222

回答by Matt Rardon

You might want to look into a JS library called phpJS.

您可能想查看一个名为 phpJS 的 JS 库。

It allows you to use the str_replace function similarly to how you would use it in PHP. There are also plenty more php functions "ported" over to JavaScript.

它允许您像在 PHP 中使用它一样使用 str_replace 函数。还有更多的 php 函数“移植”到了 JavaScript。

http://phpjs.org/functions/str_replace:527

http://phpjs.org/functions/str_replace:527

回答by Bryan Kyle

There is no way to do this in one method call, you'll have to either chain calls together, or write a function that manually does what you need.

在一个方法调用中无法做到这一点,您必须将调用链接在一起,或者编写一个手动执行所需操作的函数。

var s = "<>\n";
s = s.replace("<", "&lt;");
s = s.replace(">", "&gt;");
s = s.replace("\n", "<br/>");

回答by user113716

For the tags, you should be able to just set the content with .text()instead of .html().

对于标签,您应该可以只设置内容.text()而不是.html()

Example:http://jsfiddle.net/Phf4u/1/

示例:http : //jsfiddle.net/Phf4u/1/

var textarea = $('textarea').val().replace(/<br\s?\/?>/, '\n');

$("#output").text(textarea);

...or if you just wanted to remove the <br>elements, you could get rid of the .replace(), and temporarily make them DOM elements.

...或者如果您只是想删除<br>元素,您可以去掉.replace(),并暂时将它们设为DOM 元素。

Example:http://jsfiddle.net/Phf4u/2/

示例:http : //jsfiddle.net/Phf4u/2/

var textarea = $('textarea').val();

textarea = $('<div>').html(textarea).find('br').remove().end().html();

$("#output").text(textarea);

回答by Jose Canizares

The top answer is equivalent to doing:

最佳答案相当于做:

let text = find.reduce((acc, item, i) => {
  const regex = new RegExp(item, "g");
  return acc.replace(regex, replace[i]);
}, textarea);

Given this:

鉴于这种:

var textarea = $(this).val();
var find = ["<", ">", "\n"];
var replace = ["&lt;", "&gt;", "<br/>"];

In this case, no imperative programming is going on.

在这种情况下,没有进行命令式编程。