How to split a language string (WordPress qTranslate) in javascript

I’ve got this javascript string:

"<!--:fr-->Photos<!--:--><!--:en-->Pictures<!--:-->"

And I need to parse it to get every “language” in distinct strings. The ideal would be to have a function like:

Read More
function getText(text, lang){
    // get and return the string of the language "lang" inside the multilang string "text"
}

That I can call like that:

var frenchText = getText("<!--:fr-->Photos<!--:--><!--:en-->Pictures<!--:-->","fr");
// and would return:
// frenchText = Photos

If anyone know a good way to do that, probably with a regexp that would be FANTASTIC!!!

Related posts

Leave a Reply

3 comments

  1. I don’t think much explanation is necessary; you just add lang to a template for your regex and get the first backref (the (.*?) part). I don’t believe any part of your supplied string constitutes a reserved character. Note that you could include some error handling in case no match is found, but I’ll leave that to the OP:

    function getText(text, lang) {
      // Builds regex based on supplied language
      var re = new RegExp("<!--:" + lang + "-->(.*?)<!--:-->");
    
      // Returns first backreference
      return text.match(re)[1];
    }
    getText("<!--:fr-->Photos<!--:--><!--:en-->Pictures<!--:-->", "fr");
    // returns "Photos"
    
  2. Better to have the language set by PHP:

    var lang = '<?php echo qtrans_getLanguage(); ?>';
    function getText(text) {
      // Builds regex based on supplied language
      var re = new RegExp("<!--:" + lang + "-->(.*?)<!--:-->");
    
      // Returns first backreference
      return text.match(re)[1];
    }
    getText("<!--:fr-->Photos<!--:--><!--:en-->Pictures<!--:-->");
    
  3. As commenters from top the top asked: for strings like [:fr]french[:en]english[:] you can use the following:

    function getText(mtext, lang) {
         // Builds regex based on supplied language
        var re = new RegExp("\[:" + lang + "\](.*?)\[:","s");                          
        
        // Returns first backreference
        return mtext.match(re)[1];
    }