I am trying to create an SEO-friendly link from the input in a text input box. I do so on the blur event when the cursor leaves the input in question. I can get the text in the input to appear in the desired input (for the link), but my link isn’t hyphenated and special characters are not replaced with hyphens. I am trying to do a global string replace, but the expression expects a string, not a variable. At least from what I can tell. Also, I can’t figure out a better way to match the list of special characters, other than an array and a loop. Can someone help? My desire is to create link like this: http://domain.com/this-is-my-link. Here is my code:
$('#title').blur(function() {
var hyphenated;
hyphenated = urlTitle($(this).val());
$('#link').val(hyphenated);
});
function urlTitle(text) {
var characters = [' ', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '+', '=', '_', '{', '}', '[', ']', '|', '/', '<', '>', ',', '.', '?', '--'];
for (var i = 0; i < characters.length; i++) {
var char = String(characters[i]);
text = text.replace(/char/g, '-');
}
text = text.toLowerCase();
return text;
}
The problem lies in your escaping function:
This literally matches “char”. So if you give it
I'm building a string out of chars, it will returni'm building a string out of -s.If you want to make up a regex expression dynamically using a variable, you’ll need to build it using a string and the RegExp constructor.
Note that when using this format you do not need to specify the delimiting characters (the forward slashes before and after), and that the flags are passed as the second parameter to the constructor. I also prepended a backslash to escape any special characters you might want to replace.
Live example