我正在检查一个集合并替换所有
<Localisation container="test">To translate</Localisation>
带有文本的标签。
接下来的代码可以满足我的要求:
var localisationRegex = new RegExp("(?:<|<)(?:LocalisationKey|locale).+?(?:container|cont)=[\\\\]?(?:['\"]|("))(.+?)[\\\\]?(?:['\"]|(")).*?(?:>|>)(.*?)(?:<|<)/(?:LocalisationKey|locale)(?:>|>)", "ig");
match = localisationRegex.exec(parsedData);
while (match != null) {
var localeLength = match[0].length;
var value = match[4];
parsedData = parsedData.substr(0, match.index) + this.GetLocaleValue(value) + parsedData.substr(match.index + localeLength);
match = localisationRegex.exec(parsedData);
}
但是,当我替换的字符串比原始字符串长时,它将开始搜索下一个匹配的索引/位置是错误的(太远)。这有时会导致找不到标签。
最佳答案
抛开该方法是否好这一(重要)问题,如果是我,我会通过使用正则表达式的函数参数来避免通过源文本进行索引的问题:
var localizer = this;
var result = parsedData.replace(localisationRegex, function(_, value) {
return localizer.GetLocaleValue(value);
});
这会将标签替换为本地化内容。
关于Javascript 正则表达式(替换)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8135658/