Search code examples
javascriptjquerywordpressqtranslate

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:

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!!!


Solution

  • 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"