1

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

Ben
  • 674
  • 9
  • 21
  • This question is answered using PHP here, if anyone is interested : http://stackoverflow.com/questions/1853406/simple-regular-expression-to-return-text-from-wordpress-title-qtranslate-plugi – Mazatec Jun 25 '12 at 21:49

3 Answers3

7

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"
brymck
  • 7,555
  • 28
  • 31
0

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<!--:-->");
Ronny Sherer
  • 8,349
  • 1
  • 22
  • 9
0

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];
}
mik256
  • 1