PROWAREtech

articles » current » javascript » wordpress-slugs

JavaScript: How to Create WordPress Slugs

Create slugs with only standard characters for use in a URL or other purpose.

This code is compatible with all browsers including Internet Explorer 11 (IE11).

Use the regular expression /\W+/g to replace unwanted URL characters with a dash (-) and prevent multiple dashes running together. In other words, sanitize names and titles. Run the below code to see it in action.

See also: Use .NET C# RegEx to create WordPress slugs.


<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Create a WordPress URL Slug</title>
	<script type="text/javascript">
		function slug(input) {
			input.value = input.value.trim().replace(/\W+/g,'-').toLowerCase();
		}
		function slug2(input) {
			input.value = input.value.trim().replace(/\W+(?!$)/g,'-').toLowerCase();
		}
	</script>
</head>
<body>
	<p><input type="text" onblur="slug(this);" size="100" placeholder="Enter text to turn into a slug" /></p>
	<p><input type="text" onblur="slug2(this);" size="100" placeholder="Enter text to turn into an alternate slug version" /></p>
	<p><button type="button">OK</button></p>
</body>
</html>

PROWAREtech

Hello there! How can I help you today?
Ask any question

PROWAREtech

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
ACCEPT REJECT