Following my previous posts on How to handle non-English characters in ASP.NET MVC routes, Build pretty clean URL for your dynamic pages using JavaScript and Non English Words in URL I decided to share another simple tip that let you translate what your user inserts as content’s title (that can be a blog post title, a page name or a news headline) automatically using Google Translate API.
Let me explain it with an example. Suppose that you have a news system in Persian language and your end user enters a Persian phrase like “این یک عنوان خبر است” as the headline of a news story. From SEO point of view it’s better we include original headline words in URL (like something that I explained in this post) instead of using an integer ID or GUID (e.g. /news/?id=1 or /news/1.aspx, etc.) but as we discussed on in that post, including non-English characters in URLs is not the best way! I just wanted to have something like /news/story/this-is-a-title and didn’t want to force user translate his words into English in order to use in URL field.
A few days ago I was thinking on this topic and decided to try a trick to utilize Google Translate API (which has recently started supporting Persian language as well) to translate such titles into meaningful English phrases and then clean them using the way I described in this post.
Fortunately, thanks to Google API simplicity it was so easy and straightforward. Here’s what I wrote:
- First you should include Google API JavaScript source in your page:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
- Add this JavaScript code to your page:
$(document).ready(function() {
$("#contentPage_Title").blur(function() { parseUrl($("#contentPage_Title").val()) });
});
google.load("language", "1");
function parseUrl(url) {
$("#loadingImage").attr("style", function() { return "display: inline;" });
google.language.translate(url, "fa", "en", function(result) {
if (!result.error) {
var url = (result.translation + " ").replace(/[^a-zA-Z0-9]+/g, "-");
$("#contentPage_Url").val(url.slice(0, url.length - 1).toLowerCase());
$("#loadingImage").attr("style", function() { return "display: none;" });
}
});
}
You’re done! Now, let me explain the code a little. First using jQuery, you tell the DOM to fire parseUrl() event as soon as you enter the title and go to the next field, then, we load Google Translate service into our script, call translate function to translate from “fa” (Persian) to “en” (English) and finally clean the result using our old trick. That’s all and no magic here!
Please note that we show and hide a “Loading” element (e.g.: a loading image) before and after we call AJAX translate function. So user can see something is happening behind the scene.
