我正在尝试用多个数组替换字符串中的多个单词。字符串是“我有老婆,有汽车,有家,有船。”
function CorrectString(text){
CorrectionArr = array(
'cat'=>array('wife'),
'pen'=>array('boat', 'car')
);
}
var text = "I have a wife, a car, and a home a boat.";
text = CorrectString(text);
更换后
var text = "I have a cat, a pen, and a home a pen.";
答案 0 :(得分:0)
在JavaScript中,您可以将String.prototype.replace()与回调一起使用。
代码:
const text = 'I have a wife, a car, and a home a boat.';
const result = text.replace(/(wife)|(boat|car)/g, function (match, p1, p2) {
if (p1) return 'cat';
if (p2) return 'pen';
});
console.log(result);