skip to Main Content

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:

(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");
<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>

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(':', ' ');

2

Answers


  1. Use regex to to replace special character with empty string and use that 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(/[`~!@#$%^&*()_|+-=?;:'",.<>{}[]\/]/gi, '');
    

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

    Following is the working example:

    (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>
    Login or Signup to reply.
  2. 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,""); // 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;
    };
    
    (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;
          var clean = index.replace(/[.:?]/g,"");
          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 < $(".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");
    <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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search