如何使用jQuery将HTML页面内容转换为另一种语言并考虑特殊字符?

huangapple go评论72阅读模式
英文:

how to use jQuery to convert html page content into another language and consider special characters?

问题

以下是您要翻译的内容的中文翻译部分:

我有一个 jQuery 代码,用于转换/翻译页面内容。

这个功能很好,但是我的页面上有一些文本包含特殊字符或额外的句点。

这会导致我的代码出现问题,翻译失败。

以下是完整的代码:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->
(function($){
  $.fn.translate = function(options) {

    var that = this; //a reference to ourselves

    var settings = {
      css: "trn",
      lang: "en"/*,
      t: {
        "translate": {
          pt: "tradução",
          br: "tradução"
        }
      }*/
    };
    settings = $.extend(settings, options || {});
    if (settings.css.lastIndexOf(".", 0) !== 0)   //doesn't start with '.'
      settings.css = "." + settings.css;

    var t = settings.t;

    //public methods
    this.lang = function(l) {
      if (l) {


        settings.lang = l;
        this.translate(settings);  //translate everything
      }

      return settings.lang;
    };


    this.get = function(index) {
      var res = index;

      try {
        res = t[index][settings.lang];
      }
      catch (err) {
        //not found, return index
        return index;
      }

      if (res)
        return res;
      else
        return index;
    };

    this.g = this.get;

    // for inputs. for any attributes. like in this example i am translating placeholder.
    // you can translate any tooltip or any other attribute
    for (var i = 0; i < $(".trn").get().length; i++) {
      if ($(".trn").get()[i].nodeName == "INPUT") {
        var thisNode = $($(".trn").get()[i]);
        var placeholderValue = thisNode.attr("placeholder");

        var trn_key = thisNode.attr("data-trn-key");
        if (!trn_key) {
          trn_key = placeholderValue;
          thisNode.attr("data-trn-key", trn_key);   //store key for next time
        }
        thisNode.attr("placeholder", t[trn_key][settings.lang]);

      }

    }    
    //main
    this.find(settings.css).each(function(i) {
      var $this = $(this);

      var trn_key = $this.attr("data-trn-key");
      if (!trn_key) {
        trn_key = $this.html();


        $this.attr("data-trn-key", trn_key);   //store key for next time
      }

      $this.html(that.get(trn_key));
    });


    return this;
  };
})(jQuery);


///WE USE THE FUNCTION HERE


var dict = {
"Task": {
ge: "Aufgabe"
  }

  }

var translator = $(document).translate({lang: "en", t: dict});
translator.lang("ge");

<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<span class="trn">Task</span><br>
<span class="trn">Task:</span><br>
<span class="trn">Task...</span>

<!-- end snippet -->

如果您运行上面的代码,您会看到只有第一个文本("Task")被翻译,因为它不包含其他字符或句点。

您如何忽略所有特殊字符和句点等,只翻译单词?

我尝试了类似于这样的方法,但它不起作用:

trn_key = trn_key.replace(':', ' ');

希望这对您有所帮助。

英文:

I have a jquery code that I use to convert/translate page content.

this works fine but some of the texts on my page has special characters or extra .(dots).

and this causes an issue in my code and the translation fails.

here's the complete code:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

(function($){
$.fn.translate = function(options) {
var that = this; //a reference to ourselves
var settings = {
css: &quot;trn&quot;,
lang: &quot;en&quot;/*,
t: {
&quot;translate&quot;: {
pt: &quot;tradu&#231;&#227;o&quot;,
br: &quot;tradu&#231;&#227;o&quot;
}
}*/
};
settings = $.extend(settings, options || {});
if (settings.css.lastIndexOf(&quot;.&quot;, 0) !== 0)   //doesn&#39;t start with &#39;.&#39;
settings.css = &quot;.&quot; + settings.css;
var t = settings.t;
//public methods
this.lang = function(l) {
if (l) {
settings.lang = l;
this.translate(settings);  //translate everything
}
return settings.lang;
};
this.get = function(index) {
var res = index;
try {
res = t[index][settings.lang];
}
catch (err) {
//not found, return index
return index;
}
if (res)
return res;
else
return index;
};
this.g = this.get;
// for inputs. for any attributes. like in this example i am translating placeholder.
// you can translate any tooltip or any other attribute
for (var i = 0; i &lt; $(&quot;.trn&quot;).get().length; i++) {
if ($(&quot;.trn&quot;).get()[i].nodeName == &quot;INPUT&quot;) {
var thisNode = $($(&quot;.trn&quot;).get()[i]);
var placeholderValue = thisNode.attr(&quot;placeholder&quot;);
var trn_key = thisNode.attr(&quot;data-trn-key&quot;);
if (!trn_key) {
trn_key = placeholderValue;
thisNode.attr(&quot;data-trn-key&quot;, trn_key);   //store key for next time
}
thisNode.attr(&quot;placeholder&quot;, t[trn_key][settings.lang]);
}
}    
//main
this.find(settings.css).each(function(i) {
var $this = $(this);
var trn_key = $this.attr(&quot;data-trn-key&quot;);
if (!trn_key) {
trn_key = $this.html();
$this.attr(&quot;data-trn-key&quot;, trn_key);   //store key for next time
}
$this.html(that.get(trn_key));
});
return this;
};
})(jQuery);
///WE USE THE FUNCTION HERE
var dict = {
&quot;Task&quot;: {
ge: &quot;Aufgabe&quot;
}
}
var translator = $(document).translate({lang: &quot;en&quot;, t: dict});
translator.lang(&quot;ge&quot;);

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;span class=&quot;trn&quot;&gt;Task&lt;/span&gt;&lt;br&gt;
&lt;span class=&quot;trn&quot;&gt;Task:&lt;/span&gt;&lt;br&gt;
&lt;span class=&quot;trn&quot;&gt;Task...&lt;/span&gt;

<!-- end snippet -->

if you run the above code, you'll see that the only text that gets translated is the first one (Task) which doesn't have any other characters or dots.

How can I ignore all the special characters and the dots etc and just translate the words?

I tried something like this which doesn't work:

trn_key = trn_key.replace(&#39;:&#39;, &#39; &#39;);

答案1

得分: 1

使用正则表达式将特殊字符替换为空字符串,并使用该字符串进行翻译。如果需要将特殊字符与翻译后的单词一起显示,可以保留特殊字符。在这种情况下,我使用以下代码来替换来自https://stackoverflow.com/a/11090301/5740382的特殊字符:

trn_key.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>{}[\]\\\/]/gi, '');

以下是工作示例:

(function($){
  $.fn.translate = function(options) {

    var that = this; //a reference to ourselves
  
    var settings = {
      css: "trn",
      lang: "en"/*,
      t: {
        "translate": {
          pt: "tradução",
          br: "tradução"
        }
      }*/
    };
    settings = $.extend(settings, options || {});
    if (settings.css.lastIndexOf(".", 0) !== 0)   //doesn't start with '.'
      settings.css = "." + settings.css;
       
    var t = settings.t;
 
    //public methods
    this.lang = function(l) {
      if (l) {
      

        settings.lang = l;
        this.translate(settings);  //translate everything
      }
        
      return settings.lang;
    };


    this.get = function(index) {
      var res = index;

      try {
        res = t[index][settings.lang];
      }
      catch (err) {
        //not found, return index
        return index;
      }
      
      if (res)
        return res;
      else
        return index;
    };

    this.g = this.get;

    // for inputs. for any attributes. like in this example i am translating placeholder.
    // you can translate any tooltip or any other attribute
    for (var i = 0; i < $(".trn").get().length; i++) {
      if ($(".trn").get()[i].nodeName == "INPUT") {
        var thisNode = $($(".trn").get()[i]);
        var placeholderValue = thisNode.attr("placeholder");

        var trn_key = thisNode.attr("data-trn-key");
        if (!trn_key) {
          trn_key = placeholderValue;
          thisNode.attr("data-trn-key", trn_key);   //store key for next time
        }
        thisNode.attr("placeholder", t[trn_key][settings.lang]);

      }
          
    }    
    //main
    this.find(settings.css).each(function(i) {
      var $this = $(this);
      


      var trn_key = $this.attr("data-trn-key");
      if (!trn_key) {
        trn_key = $this.html();
        $this.attr("data-trn-key", trn_key);   //store key for next time
      }

      let currentWord = trn_key.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>{}[\]\\\/]/gi, '');
      let currentSpecialCharacter = trn_key.replace(currentWord, '');
      $this.html(that.get(currentWord) + currentSpecialCharacter);

    });
    
    
    return this;
  };
})(jQuery);



///WE USE THE FUNCTION HERE


var dict = {
"Task": {
ge: "Aufgabe"
  }
  
  }

var translator = $(document).translate({lang: "en", t: dict});
translator.lang("ge");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<span class="trn">Task</span><br>
<span class="trn">Task:</span><br>
<span class="trn">Task...</span>
英文:

Use regex to replace special character with empty string and use that string to translate. Similarly, hold the special character if you need to be displayed along with translated word. In this case I have used

trn_key.replace(/[`~!@#$%^&amp;*()_|+\-=?;:&#39;&quot;,.&lt;&gt;\{\}\[\]\\\/]/gi, &#39;&#39;);

to replace special character taken from https://stackoverflow.com/a/11090301/5740382

Following is the working example:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

(function($){
$.fn.translate = function(options) {
var that = this; //a reference to ourselves
var settings = {
css: &quot;trn&quot;,
lang: &quot;en&quot;/*,
t: {
&quot;translate&quot;: {
pt: &quot;tradu&#231;&#227;o&quot;,
br: &quot;tradu&#231;&#227;o&quot;
}
}*/
};
settings = $.extend(settings, options || {});
if (settings.css.lastIndexOf(&quot;.&quot;, 0) !== 0)   //doesn&#39;t start with &#39;.&#39;
settings.css = &quot;.&quot; + settings.css;
var t = settings.t;
//public methods
this.lang = function(l) {
if (l) {
settings.lang = l;
this.translate(settings);  //translate everything
}
return settings.lang;
};
this.get = function(index) {
var res = index;
try {
res = t[index][settings.lang];
}
catch (err) {
//not found, return index
return index;
}
if (res)
return res;
else
return index;
};
this.g = this.get;
// for inputs. for any attributes. like in this example i am translating placeholder.
// you can translate any tooltip or any other attribute
for (var i = 0; i &lt; $(&quot;.trn&quot;).get().length; i++) {
if ($(&quot;.trn&quot;).get()[i].nodeName == &quot;INPUT&quot;) {
var thisNode = $($(&quot;.trn&quot;).get()[i]);
var placeholderValue = thisNode.attr(&quot;placeholder&quot;);
var trn_key = thisNode.attr(&quot;data-trn-key&quot;);
if (!trn_key) {
trn_key = placeholderValue;
thisNode.attr(&quot;data-trn-key&quot;, trn_key);   //store key for next time
}
thisNode.attr(&quot;placeholder&quot;, t[trn_key][settings.lang]);
}
}    
//main
this.find(settings.css).each(function(i) {
var $this = $(this);
var trn_key = $this.attr(&quot;data-trn-key&quot;);
if (!trn_key) {
trn_key = $this.html();
$this.attr(&quot;data-trn-key&quot;, trn_key);   //store key for next time
}
let currentWord = trn_key.replace(/[`~!@#$%^&amp;*()_|+\-=?;:&#39;&quot;,.&lt;&gt;\{\}\[\]\\\/]/gi, &#39;&#39;);
let currentSpecialCharacter = trn_key.replace(currentWord, &#39;&#39;);
$this.html(that.get(currentWord) + currentSpecialCharacter);
});
return this;
};
})(jQuery);
///WE USE THE FUNCTION HERE
var dict = {
&quot;Task&quot;: {
ge: &quot;Aufgabe&quot;
}
}
var translator = $(document).translate({lang: &quot;en&quot;, t: dict});
translator.lang(&quot;ge&quot;);

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;span class=&quot;trn&quot;&gt;Task&lt;/span&gt;&lt;br&gt;
&lt;span class=&quot;trn&quot;&gt;Task:&lt;/span&gt;&lt;br&gt;
&lt;span class=&quot;trn&quot;&gt;Task...&lt;/span&gt;

<!-- end snippet -->

答案2

得分: 1

以下是翻译的内容:

  1. You can remove them from the lookup key

    • 你可以从查找键中移除它们
  2. Add the chars you want or reverse something like /^[\p{L}]+$/u

    • 添加你想要的字符或反转类似 /^[\p{L}]+$/u 的内容
  3. this.get = function(index) {

    • this.get = function(index) {
  4. var res = index;

    • var res = index;
  5. var clean = index.replace(/[.:?]/g, "");

    • var clean = index.replace(/[.:?]/g, "");
  6. res = t[clean][settings.lang];

    • res = t[clean][settings.lang];
  7. //not found, return index

    • //未找到,返回索引
  8. if (res)

    • if (res)
  9. return index.split(clean).join(res);

    • return index.split(clean).join(res);
  10. else

    • else
  11. return index;

    • return index;
  12. (function($){

    • (function($){
  13. $.fn.translate = function(options) {

    • $.fn.translate = function(options) {
  14. var that = this; //a reference to ourselves

    • var that = this; //对自身的引用
  15. var settings = {

    • var settings = {
  16. css: "trn",

    • css: "trn",
  17. lang: "en"/*,

    • lang: "en"/*,
  18. t: {

    • t: {
  19. "translate": {

    • "translate": {
  20. pt: "tradução",

    • pt: "tradução",
  21. br: "tradução"

    • br: "tradução"
  22. }

    • }
  23. }

    • }
  24. settings = $.extend(settings, options || {});

    • settings = $.extend(settings, options || {});
  25. if (settings.css.lastIndexOf(".", 0) !== 0) //doesn't start with '.'

    • if (settings.css.lastIndexOf(".", 0) !== 0) //不以'.'开头
  26. settings.css = "." + settings.css;

    • settings.css = "." + settings.css;
  27. var t = settings.t;

    • var t = settings.t;
  28. this.lang = function(l) {

    • this.lang = function(l) {
  29. if (l) {

    • if (l) {
  30. settings.lang = l;

    • settings.lang = l;
  31. this.translate(settings); //translate everything

    • this.translate(settings); //翻译所有内容
  32. }

    • }
  33. return settings.lang;

    • return settings.lang;
  34. }

    • }
  35. this.get = function(index) {

    • this.get = function(index) {
  36. var res = index;

    • var res = index;
  37. var clean = index.replace(/[.:?]/g,"");

    • var clean = index.replace(/[.:?]/g,"");
  38. //not found, return index

    • //未找到,返回索引
  39. return index;

    • return index;
  40. }

    • }
  41. this.g = this.get;

    • this.g = this.get;
  42. for (var i = 0; i < $(".trn").get().length; i++) {

    • for (var i = 0; i < $(".trn").get().length; i++) {
  43. if ($(".trn").get()[i].nodeName == "INPUT") {

    • if ($(".trn").get()[i].nodeName == "INPUT") {
  44. var thisNode = $($(".trn").get()[i]);

    • var thisNode = $($(".trn").get()[i]);
  45. var placeholderValue = thisNode.attr("placeholder");

    • var placeholderValue = thisNode.attr("placeholder");
  46. var trn_key = thisNode.attr("data-trn-key");

    • var trn_key = thisNode.attr("data-trn-key");
  47. thisNode.attr("data-trn-key", trn_key); //store key for next time

    • thisNode.attr("data-trn-key", trn_key); //存储键以供下次使用
  48. thisNode.attr("placeholder", t[trn_key][settings.lang]);

    • thisNode.attr("placeholder", t[trn_key][settings.lang]);
  49. }

    • }
  50. }

    • }
  51. this.find(settings.css).each(function(i) {

    • this.find(settings.css).each(function(i) {
  52. var $this = $(this);

    • var $this = $(this);
  53. $this.html(that.get(trn_key));

    • $this.html(that.get(trn_key));
  54. });

    • });
  55. return this;

    • return this;
  56. };

    • };
  57. })(jQuery);

    • })(jQuery);
  58. ///WE USE THE FUNCTION HERE

    • ///在这里使用该函数
  59. var dict = {

    • var dict = {
  60. "Task": {

    • "Task": {
  61. ge: "Aufgabe"

    • ge: "Aufgabe"
  62. }

    • }
  63. }

    • }
  64. var translator = $(document).translate({lang: "en", t: dict});

    • var translator = $(document).translate({lang: "en", t: dict});
  65. translator.lang("ge");

    • translator.lang("ge");
  66. Task

    • Task
  67. Task:

    • Task:
  68. Task...

    • Task...
英文:

You can remove them from the lookup key

Add the chars you want or reverse something like /^[\p{L}]+$/u

this.get = function(index) {
var res = index;
var clean = index.replace(/[\.:\?]/g,&quot;&quot;); // added - 
try {
res = t[clean][settings.lang]; // changed
}
catch (err) {
//not found, return index
return index;
}
if (res)
return index.split(clean).join(res); // changed
else
return index;
};

<!-- begin snippet: js hide: trueconsole: true babel: false -->

<!-- language: lang-js -->

(function($){
$.fn.translate = function(options) {
var that = this; //a reference to ourselves
var settings = {
css: &quot;trn&quot;,
lang: &quot;en&quot;/*,
t: {
&quot;translate&quot;: {
pt: &quot;tradu&#231;&#227;o&quot;,
br: &quot;tradu&#231;&#227;o&quot;
}
}*/
};
settings = $.extend(settings, options || {});
if (settings.css.lastIndexOf(&quot;.&quot;, 0) !== 0)   //doesn&#39;t start with &#39;.&#39;
settings.css = &quot;.&quot; + settings.css;
var t = settings.t;
//public methods
this.lang = function(l) {
if (l) {
settings.lang = l;
this.translate(settings);  //translate everything
}
return settings.lang;
};
this.get = function(index) {
var res = index;
var clean = index.replace(/[\.:\?]/g,&quot;&quot;);
try {
res = t[clean][settings.lang];
}
catch (err) {
//not found, return index
return index;
}
if (res)
return index.split(clean).join(res)
else
return index;
};
this.g = this.get;
// for inputs. for any attributes. like in this example i am translating placeholder.
// you can translate any tooltip or any other attribute
for (var i = 0; i &lt; $(&quot;.trn&quot;).get().length; i++) {
if ($(&quot;.trn&quot;).get()[i].nodeName == &quot;INPUT&quot;) {
var thisNode = $($(&quot;.trn&quot;).get()[i]);
var placeholderValue = thisNode.attr(&quot;placeholder&quot;);
var trn_key = thisNode.attr(&quot;data-trn-key&quot;);
if (!trn_key) {
trn_key = placeholderValue;
thisNode.attr(&quot;data-trn-key&quot;, trn_key);   //store key for next time
}
thisNode.attr(&quot;placeholder&quot;, t[trn_key][settings.lang]);
}
}    
//main
this.find(settings.css).each(function(i) {
var $this = $(this);
var trn_key = $this.attr(&quot;data-trn-key&quot;);
if (!trn_key) {
trn_key = $this.html();
$this.attr(&quot;data-trn-key&quot;, trn_key);   //store key for next time
}
$this.html(that.get(trn_key));
});
return this;
};
})(jQuery);
///WE USE THE FUNCTION HERE
var dict = {
&quot;Task&quot;: {
ge: &quot;Aufgabe&quot;
}
}
var translator = $(document).translate({lang: &quot;en&quot;, t: dict});
translator.lang(&quot;ge&quot;);

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;span class=&quot;trn&quot;&gt;Task&lt;/span&gt;&lt;br&gt;
&lt;span class=&quot;trn&quot;&gt;Task:&lt;/span&gt;&lt;br&gt;
&lt;span class=&quot;trn&quot;&gt;Task...&lt;/span&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月6日 17:24:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76627357.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定