68

I have a string like this:

var str = "I'm a very^ we!rd* Str!ng.";

What I would like to do is removing all special characters from the above string and replace spaces and in case they are being typed, underscores, with a - character.

The above string would look like this after the "transformation":

var str = 'im-a-very-werd-strng';
Jasper
  • 75,717
  • 14
  • 151
  • 146
Roel
  • 1,462
  • 4
  • 19
  • 31

8 Answers8

141

replace(/[^a-z0-9\s]/gi, '') will filter the string down to just alphanumeric values and replace(/[_\s]/g, '-') will replace underscores and spaces with hyphens:

str.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-')

Source for Regex: RegEx for Javascript to allow only alphanumeric

Here is a demo: http://jsfiddle.net/vNfrk/

Community
  • 1
  • 1
Jasper
  • 75,717
  • 14
  • 151
  • 146
  • 2
    *Comment from [Daniel Przybylowski](http://stackoverflow.com/users/3941987/daniel-przybylowski):* It seems that the underscore is removed by the first regex. So the second one could be like: replace(/\s{1,}/g, '-') The reason for a quantifier is to replace one or more spaces with '-'. Why ? Imagine string like "something & something". – Artjom B. Aug 14 '14 at 16:00
  • 1
    @HereToLearn_ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#special-white-space – Jasper Sep 28 '15 at 15:45
  • replace(/[_\s+]/g, '-') to replace multiple spaces with only one dash could come in handy – Rossitten Apr 01 '16 at 06:33
  • Thanks, @Jasper it's working perfectly. But if in string have more than one - (dash) then how to remove second dash. – heySushil Nov 23 '19 at 05:59
  • This strips out hyphens and underscores and only replaces spaces with hyphens. Here's a version that replaces underscores and spaces with hyphens and keeps existing hyphens intact: `str.replace(/[^a-z0-9\s-_]/gi, '').replace(/[\s_-]/g, '-')` – Must Impress May 07 '23 at 06:59
25

Assuming by "special" you mean non-word characters, then that is pretty easy.

str = str.replace(/[_\W]+/g, "-")
Ilia G
  • 10,043
  • 2
  • 40
  • 59
  • I want to remove the non-word characters (or replace them with 'nothing'). I want to keep the numbers and normal letters and want to replace the spaces and underscores with a horizontal stripe. – Roel Jan 23 '12 at 22:42
  • That's the most powerful answer. Simple yet powerful..! – Ari Feb 05 '14 at 05:20
  • 1
    Worth pointing out that unlike all the above answers this one actually deals with "foo & bar" like this "foo-bar" and not like this "foo--bar". Short, simple and does the job perfect! – radu.luchian Aug 27 '14 at 12:31
  • Will it work on word characters but non utf 8 ? Like ç ş ğ ü ö – user3304007 Aug 27 '17 at 10:46
14
str.toLowerCase().replace(/[\*\^\'\!]/g, '').split(' ').join('-')
Grace Huang
  • 5,355
  • 5
  • 30
  • 52
6

Remove numbers, underscore, white-spaces and special characters from the string sentence.

str.replace(/[0-9`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi,'');

Demo

5

this will remove all the special character

 str.replace(/[_\W]+/g, "");

this is really helpful and solve my issue. Please run the below code and ensure it works

var str="hello world !#to&you%*()";
console.log(str.replace(/[_\W]+/g, ""));
Jayakumar Thangavel
  • 1,884
  • 1
  • 22
  • 29
Amit Sharma
  • 1,775
  • 3
  • 11
  • 20
2

Since I can't comment on Jasper's answer, I'd like to point out a small bug in his solution:

str.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-');

The problem is that first code removes all the hyphens and then tries to replace them :) You should reverse the replace calls and also add hyphen to second replace regex. Like this:

str.replace(/[_\s]/g, '-').replace(/[^a-z0-9-\s]/gi, '');
Marko Sulamägi
  • 884
  • 1
  • 8
  • 14
2

Remove/Replace all special chars in Jquery :

If

str = My name is "Ghanshyam" and from "java" background

and want to remove all special chars (") then use this

str=str.replace(/"/g,' ')

result:

My name is Ghanshyam and from java background

Where g means Global

cigien
  • 57,834
  • 11
  • 73
  • 112
0
var str = "I'm a very^ we!rd* Str!ng.";
$('body').html(str.replace(/[^a-z0-9\s]/gi, " ").replace(/^\s+|\s+$|\s+(?=\s)/g, "").replace(/[_\s]/g, "-").toLowerCase());

First regex remove special characters with spaces than remove extra spaces from string and the last regex replace space with "-"

oguz ismail
  • 1
  • 16
  • 47
  • 69
  • 4
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Yunnosch Feb 04 '21 at 07:32