JQuery / Javascript:新的RegExp()停止循环

问题描述 投票:0回答:3

我正在创建一个翻译函数,我想在一个对象中轻松添加翻译,然后在$("body").html()内部全局更改,问题是,当我在for循环中使用new RegExp()时,它会在第一次迭代后切断循环。

if (window.location.href.indexOf("sv") > -1) {
    //CUSTOM TRANSLATIONS

    var translations = {
        'All': 'alla',
        'Filter Members': 'Filtrera medlemar',
    }



    for (var key in translations) {
        if (translations.hasOwnProperty(key)) {

            console.log(key + " -> " + translations[key]);
            $body = jQuery("body");
            replaceThis = new RegExp(key, "g");

            alert(replaceThis);

            $body.html($body.html().replace(replaceThis, translations[key]));

        }
    }

}
javascript jquery regex for-loop
3个回答
2
投票

看来你的body标签里面有脚本,因此你的脚本会遇到错误。尝试在所有html上添加一个html容器元素,然后对该容器元素而不是body执行操作。

var translations = {
  'All': 'alla',
  'Filter Members': 'Filtrera medlemar'
};

for (var key in translations) {
  if (translations.hasOwnProperty(key)) {

    //console.log(key + " -> " + translations[key]);
    $container = jQuery(".container");
    replaceThis = new RegExp(key, "g");

    //alert(replaceThis);

    $container.html($container.html().replace(replaceThis, translations[key]));

  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <div>All</div>
  <div>Filter Members</div>
  <div>All</div>
  <div>Filter Members</div>
</div>

1
投票

当您使用二维数组时,您需要将2个参数绑定到您的函数,一个用于键,一个用于值。这个例子应该有效。

jQuery.each( translations, function( key, value ) {
  console.log(key + " -> " + translations[key]);
  $body =  jQuery("body");
  replaceThis = new RegExp(key, "g");
  alert(replaceThis);
  $body.html($body.html().replace(replaceThis, translations[key]));
});

0
投票

Issues

  • 不要针对<html><body>标签,或窗口或文档 - 针对嵌套在<body>中的元素,如Aggarwal先生的answer和iArcadia的评论所暗示的那样。
  • iArcadia的评论还指出,有多余的代码:translations.hasOwnProperty(key)
  • 正如Stribiżew先生在评论中指出的那样,通过RegExp对象传递的搜索字符串应该被转义。在不转义给定字符串的情况下,会产生不希望的结果,例如: 匹配子串(例如搜索字符串:所有匹配项:Alligator) 匹配HTML标记(例如搜索字符串:类匹配:<div class="...>

Solution

我刚写了一个名为.translateWord()的快速jQuery插件:

用法:$(selector).translateWord(matrix) 帕拉姆: selector {string}:CSS / jQuery选择器字符串语法 matrix {array}:键/值对的二维数组

它将给定的数组(矩阵)数组转换为ES6 Map(字典)。每个键(关键字)都被转义(转义):

`(?!(?:[^<]+>|[^>]+<\\/a>))\\b(${keyword})\\b`

然后传递一个RegExp()对象(正则表达式),后者又搜索并替换对应于字典键的字典值。

let en2sv = [
  ['them', 'dem'],
  ['you', 'du'],
  ["I'm", 'Jag är'],
  ['was', 'var']
];

(function($) {
  $.fn.translateWord = function(matrix) {
    let dictionary = new Map(matrix);
    for (let keyword of dictionary.keys()) {
      let string = $(this).html();
      let escape = `(?!(?:[^<]+>|[^>]+<\\/a>))\\b(${keyword})\\b`;
      let regex = new RegExp(escape, "gi");
      let html = string.replace(regex, `<mark>${dictionary.get(keyword)}</mark>`);
      $(this).html(html);
    }
  }
})(jQuery);

$('main').translateWord(en2sv);
<main>
  <article>
    <h1>HEISENBERG IPSUM</h1>
    <section>
      <h2>I</h2>
      <p>What? What do you want?! No. Don't even tell me you're hungry. Don't go there. Hahaha! Are you mad doggin' them, Tio? What, you don't like them? One ding. That means yes. Tio don't like you. Why don't you like them, Tio? You don't trust them? Why
        don't you trust them, Tio? BULLSHIT! MY TIO DOES NOT LIE!</p>
    </section>
    <section>
      <h2>II</h2>
      <p>You... are trouble. I'm sorry the kid here doesn't see it, but I sure as hell do. You are a time bomb. Tick, tick, ticking. And I have no intention of being around for the boom. Well... you know how they say, it's been a pleasure? It hasn't.</p>
    </section>
    <section>
      <h2>III</h2>
      <p>Walter, I'm your lawyer. Anything you say to me is totally privileged. I'm not in the shakedown racket. I'm a lawyer. Even drug dealers need lawyers, right? Especially drug dealers.</p>
    </section>
    <section>
      <h2>IV</h2>
      <p>My partner was about to get himself shot. I intervened. He was angry because those two dealers of yours had just murdered an eleven year-old boy. Then again, maybe he thought it was you who gave the order. </p>
    </section>
  </article>
</main>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
© www.soinside.com 2019 - 2024. All rights reserved.