JavaScript string replace for post slug
August 22, 2005
/ Filed under: JavaScript, Tutorials
My own administration panel, for this blog, helps me insert new entries into my database. On my "Add New Entry" form, I have many fields. Two important fields are headline and post slug. The headline is, obviously, the headline of the entry. The post slug is the name that appears in the permanent URL for the entry. For example, if you look up to the address bar, in the browser, you’ll see the permanent URL, for this entry. You’ll notice a handful of useful information, such as the year, month, and day - but at the very end is the post slug. It’s basically the headline "crunched down." In other words, the headline for this entry is JavaScript string replace for post slug. So, the post slug is therefore: javascript-string-replace-for-post-slug. Notice how the entire phrase is lower case. Also, all spaces have been removed, and replaced with a dash (-). When I go to post a new entry, I don’t like to have to type things twice. So, after I enter the headline, I have some simple JavaScript automatically enter the post slug. For example, try entering a headline in the text box below, and then click out of the box, and watch how the text is automatically copied over to the post slug field: The HTMLIn the headline field, in the HTML form, we have something similar to this:
Notice the onBlur attribute calls a function named headline_to_postslug, which is a JavaScript function that takes three parameters. The JavaScriptIt’s not perfectOf course, it’s not perfect. The post slug can only contain letters, numbers, or dashes - but the headline might contain characters like double quotes ("), single quotes (‘ ’), parenthesis, commas (,), and much more. Currently, the JavaScript function I created does not check for all those other characters. It simply checks for spaces. And that’s OK. The majority of my headlines won’t contain all of those other characters - and I don’t mind if I have to edit the post slug field, in the case that those characters do exist, in the headline. And, obviously, if we wanted, we could easily add some more JavaScript to make those other characters automatically disappear, too. But, for now, we’ll just keep it simple.
Comments/Mentions
|
Editor Picks
Email NewsletterSubscribe to the digest newsletter to receive posts by email: Recent Comments
Advertisements
|
I do that based on a php function so that clients don't need to have javascript going.
Also it is a good idea to check input because the javascript stuff can be changed.
/off topic:
Have you been getting any spam through your contact form?
Also you have "" at the very top left hand side of your website, I've had that issue before, something to do with Dreamweaver I think.