简体   繁体   English

Javascript正则表达式(替换)问题

[英]Javascript Regex (replace) Issue

I am checking a collection and replacing all 我正在检查集合并替换所有

<Localisation container="test">To translate</Localisation>

tags with text. 带有文本的标签。

The next codes does what I want: 接下来的代码实现了我想要的:

var localisationRegex = new RegExp("(?:<|&lt;)(?:LocalisationKey|locale).+?(?:container|cont)=[\\\\]?(?:['\"]|(&quot;))(.+?)[\\\\]?(?:['\"]|(&quot;)).*?(?:>|&gt;)(.*?)(?:<|&lt;)/(?:LocalisationKey|locale)(?:>|&gt;)", "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);
            }

But, when the the string I replace with, Is longer then the original string, the index/place where it will start to search for the next match, is wrong (to far). 但是,当我替换的字符串比原始字符串长时,它将开始搜索下一个匹配项的索引/位置是错误的(到目前为止)。 This sometimes leads to tags not found. 有时这会导致找不到标签。

Setting aside the (important) question as to whether the approach is a good one, if it were me I'd avoid the problem of indexing through the source text by using a function argument to the regex: 撇开(重要的)问题,关于该方法是否是一种好的方法,如果是我,我将避免使用使用正则表达式的函数参数来索引源文本的问题:

var localizer = this;
var result = parsedData.replace(localisationRegex, function(_, value) {
  return localizer.GetLocaleValue(value);
});

That will replace the tags with the localized content. 这将用本地化的内容替换标签。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM