一次替换多个字符串 [英] Replace multiple strings at once
本文介绍了一次替换多个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 JavaScript 中有一个简单的等价物吗?
Is there an easy equivalent to this in JavaScript?
$find = array("<", ">", "
");
$replace = array("<", ">", "<br/>");
$textarea = str_replace($find, $replace, $textarea);
这是使用 PHP 的 str_replace
,它允许您使用一组单词来查找和替换.我可以使用 JavaScript/jQuery 做这样的事情吗?
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?
...
var textarea = $(this).val();
// string replace here
$("#output").html(textarea);
...
推荐答案
你可以用你自己的函数扩展 String 对象来满足你的需要(如果缺少功能,很有用):
You could extend the String object with your own function that does what you need (useful if there's ever missing functionality):
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;
};
要使用该函数,它会类似于您的 PHP 示例:
To use the function it'd be similar to your PHP example:
var textarea = $(this).val();
var find = ["<", ">", "
"];
var replace = ["<", ">", "<br/>"];
textarea = textarea.replaceArray(find, replace);
这篇关于一次替换多个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文