While working on a recent project with the excellent Prototype and Scriptaculous javascript libraries, I came across a frustrating error in IE7 (and I’m sure IE6 although I didn’t test it). The page worked beautifully in firefox but came up with “Expected identifier, string or number” on IE.
Normal debugging procedures (firebug, web developer toolbar) failed to show where my error was. To its credit, the Microsoft script debugger actually showed me the function with the error but at that time I didn’t see it as an error. After a couple of hours of hair-pulling and googling, I came across this post.
Apparently, a comma in my function was the culprit. My problem code was:
function xajax_getOptions(badgeId) {
new Ajax.Request($F("absolute-url") + "/ajax/options",
{
method:'post',
parameters: {catid: badgeId},
onSuccess: function(transport){
var response = transport.responseText;
$("badgecell").innerHTML = response;
getBadgeImage();
},
//onFailure: function(){ alert("an error occurred"); }
});
}
Notice that I commented out the onFailure parameter without taking out the comma at the end. Firefox ignored that, IE choked.
A big thank you to Khlo for showing the way.
CodeIgniter has got a nifty url_title() function as part of the url helpers and I’ve frequently used this. This takes in a title, sentence, whatever and “creates a human-friendly URL string”.
For instance, passing “What time is it?” as a parameter will return “what-time-is-it” and this can be used in a url string for better search engine indexing and a neater and more professional url structure.
I needed to do the same with javascript.
The HTML:
<form action="#" method="post">
<p>
<label for="title">Title</label>
<input name="title" id="title" value="" onblur="makeFriendly()" onkeyup="makeFriendly();" />
</p>
<p>
<label for="friendly">Friendly URL</label>
<input name="friendly" id="friendly" value="" />
</p>
<p>
<input type="submit" name="submit" value="Save friendly URL" />
</p>
</form>
The Javascript:
<script type=“text/javascript“ language=“javascript“>
function makeFriendly() {
var title = document.getElementById(“title“);
var friendly = document.getElementById(“friendly“);
friendly.value = cleanUp(title.value);
}
function cleanUp(str) {
str = str.toLowerCase(); //change everything to lowercase
str = str.replace(/^s+|s+$/g, ““); //trim leading and trailing spaces
str = str.replace(/[_s]+/g, “-“); //change all spaces and underscores to a hyphen
str = str.replace(/[^a-z0-9-]+/g, ““); //remove all non-alphanumeric characters except the hyphen
str = str.replace(/[-]+/g, “-“); //replace multiple instances of the hyphen with a single instance
str = str.replace(/^-+|-+$/g, ““); //trim leading and trailing hyphens
return str;
}
</script>
So there you have it. A Javascript version of url_title().
Update: This one-liner (using the prototype library) does the same thing
$("title").value = $F("friendly").strip().gsub(/s+/, '-').gsub(/[^a-zA-Z0-9-]+/, '').toLowerCase();