views:

28

answers:

2

Hi ,

I am using google ajax based translation API like in the below example.

google.load("language", "1");

    function initialize() {
      var text = document.getElementById("text").innerHTML;
      google.language.detect(text, function(result) {
        if (!result.error && result.language) {
          google.language.translate(text, result.language, "en",
                                    function(result) {
            var translated = document.getElementById("translation");
            if (result.translation) {
              translated.innerHTML = result.translation;
            }
          });
        }
      });
    }
    google.setOnLoadCallback(initialize);

When I send string like " how are you? "

The transaltion what I get is like "xxx xxx xxxxxxx" . the spaces in the original string are trimmed.How do I prevent it from happening ?

A: 

You can't. What you can do is work around it by regexing the leading/trailing space into scratch variables and prepending/appending it back on after Google is done.

Benjamin Franz
+1  A: 

Try:

function initialize() {
  var text = document.getElementById("text").innerHTML;
  var spaceMatch = text.match(/^(\s*).*?(\s*)$/);
  google.language.detect(text, function(result) {
    if (!result.error && result.language) {
      google.language.translate(text, result.language, "en",
                                function(result) {
        var translated = document.getElementById("translation");
        if (result.translation) {
          translated.innerHTML = spaceMatch[1] + result.translation + spaceMatch[2];
        }
      });
    }
  });
}
Matthew Flaschen