Huge string replace in JavaScript?

萝らか妹 提交于 2019-12-06 04:11:29

I don't know much about speed in JavaScript, or why this can't be configured correctly on the server, but here's one way to do it.

Interactive Demo

First we turn everything into an object, so we can look up translations.

var map = {};
for (var i=0; i<toReplace.length; i++) {
  map[toReplace[i]] = replaceWith[i];
}

Then we join our keys into a regular expression
(note: they must be sorted longest-first, code in the demo).

var expression = new RegExp(toReplace.join("|"), "g");

In the replace function, we can subsitute matches for results. This is as simple as looking them up in our map.

function doReplace(source) {
  return source.replace(expression, function(m) {
    return map[m];
  });
}

var result = doReplace("Señor");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!