Koen Hollander
Koen Hollander

Reputation: 1711

How to allow a-z 0-9 and a dash in regex

I have a CMS and want to create a nice slug in the search engine

I've tried to achieve it with a regex, but it looks like it is ignoring to totally

A little example:

$('#name_nl').blur(function() {
        var string = $('#name_nl').val();
        string = string.replace(/[A-Za-z0-9]{0,1}[A-Za-z0-9-]/g,'');
        $('#slug_nl').val(string.toLowerCase());
        //console.log("Blurred name_nl");
    });

In the above example it should give the output where I allow a first character to be A-Z a-z and 0-9 and after that the - is also allowed.

But when I test it on (WI-FI) network i get (wi-fi) network

I already tested it on a regex tester, it looks great But Javascript does not like it...

https://regex101.com/r/ev3uFR/2

How can I remove every special character, instead of the - and remove them as first and last character?

Upvotes: 2

Views: 3086

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626896

I suggest removing hyphens at the start and end of the string, and remove all chars other than alphanumeric and - in any other contexts:

.replace(/^-+|-+$|[^A-Za-z0-9-]+/g, "")

See the regex demo.

Details

  • ^-+ - start of string position and 1 or more - chars there
  • | -or
  • -+$ - 1 or more hyphens at the end of the string
  • | - or
  • [^A-Za-z0-9-]+ - 1 or more ASCII letters, digits or/and - chars.

JS demo:

console.log("a(WI-FI) netwerken".replace(/^-+|-+$|[^A-Za-z0-9-]+/g, ""));
console.log("--a(WI-FI) netwerken".replace(/^-+|-+$|[^A-Za-z0-9-]+/g, ""));
console.log("a(WI-FI) netwerken--".replace(/^-+|-+$|[^A-Za-z0-9-]+/g, ""));

Upvotes: 5

Related Questions