Karem
Karem

Reputation: 18103

Javascript Regex remove specialchars except - and æøå

I got this:

var stringToReplace = 'æøasdasd\89-asdasd sse';
var desired = stringToReplace.replace(/[^\w\s]/gi, '');
alert(desired);

I found the replace rule from another SO question.

This works fine, it gives output:

asdasd89asdasd sse

Although I would like to set up additional rules:

  1. Keep æøå characters
  2. Keep - character
  3. Turn whitespace/space into a - character

So the output would be:

æøåasdasd89-asdasd-sse

I know I can run an extra line: stringtoReplace.replace(' ', '-');

to accomplish my 3) goal - but I dont know what to do with the 1 and 2), since I am not into regex expressions ?

Upvotes: 1

Views: 1960

Answers (3)

anubhava
anubhava

Reputation: 785058

This should work:

str = str.replace(/[^æøå\w -]+/g, '').replace(/ +/g, '-');

Live Demo: http://ideone.com/d60qrX

Upvotes: 2

skajfes
skajfes

Reputation: 8265

You can just add the special characters to the exclusion list.

/[^\w\sæøå-]/gi

Fiddle with example here.

And as you said - you can use another replace to replace spaces with dashes

Upvotes: 1

Nightfirecat
Nightfirecat

Reputation: 11610

Your original regex [^\w\s] targets any character which isn't a word or whitespace character (-, for example). To include other characters in this regex's 'whitelist', simply add them to that character group:

stringToReplace.replace(/[^\w\sæøå-]/gi, '');

As for replacing spaces with hyphens, you cannot do both in a single regex. You can, however, use a string replacement afterwards to solve that.

stringToReplace.replace(" ","-"); 

Upvotes: 0

Related Questions