Question

I have a field in my form in which I provide the name of my new page which I'm adding to my CMS.

I have a PHP code here which lowers case, sets '-' instead of ' ', and makes a short URL look nice:

$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
$clean = preg_replace("/[^a-zA-Z0-9\/_| -]/", '', $clean);
$clean = strtolower(trim($clean, '-'));
$clean = preg_replace("/[\/_| -]+/", '-', $clean);

I am NOT EXPERIENCED with JavaScript's RegEx, so can anyone help me convert this piece of PHP code to JavaScript.

Thank you all!

Was it helpful?

Solution

All in one go:

var string = "The   new page's future name!"
,   clean = string.replace(/(^\-+|[^a-zA-Z0-9\/_| -]+|\-+$)/g, '')
            .toLowerCase()
            .replace(/[\/_| -]+/g, '-')
;
console.log(clean); // "the-new-pages-future-name"

The first replace takes care of all unwanted characters AND trims all extra dashes at start and end. The second replace replaces all (groups of) slashes, underscores, pipes and spaces by a hyphen.

OTHER TIPS

Try this:

var string = "Some string to clean up";
string.replace(/[^a-zA-Z0-9-]+/g, '-').toLowerCase();

In my browser console it yields

"some-string-to-clean-up"

You shouldn't need to convert between charsets in javascript. Here is a very literal version of the rest of it.

clean = clean.replace(/[^a-zA-Z0-9\/_| -]/g, '');
clean = clean.replace(/^[\-]+/, ''); // trim start
clean = clean.replace(/[\-]+$/, ''); // trim end
clean = clean.toLowerCase();
clean = clean.replace(/[\/_| -]+/g, '-');

Or in one statement

 clean = clean.replace(/[^a-zA-Z0-9\/_| -]/g, '').replace(/^[\-]+/, '').replace(/[\-]+$/, '').toLowerCase().replace(/[\/_| -]+/g, '-');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top