Reputation: 413
how to remove special character except "/" from a string? What is the regex should i use?
"/[^a-z0-9_\s-]/"
Im using this regex. It is not working.
Upvotes: 0
Views: 1272
Reputation: 24812
When using /
in a /.../
regex syntax you need to escape it with a backslash. Alternatively you can use the RegExp
constructor to avoid having to escape the /
: both /[^\/]/
and new RegExp("[^/]")
will match any character but /
.
To remove any special character but /
, it depends on what you call a special character but I would use /[^a-zA-Z0-9\/]/
.
If you don't mind underscores you can use /[^\w\/]/
.
It matches only one character, so you will probably want to use the g
global flag : /[^a-zA-Z0-9\/]/g
or new RegExp("[^a-zA-Z0-9/]", "g")
Upvotes: 6
Reputation: 68443
Try this as well
input.replace(/\W/g, function(match){ return (match == "/" ? match : "") });
function replaceExceptChar( input, specialChar )
{
return input.replace(/\W/g, function(match){ return (match == specialChar ? match : "") });
}
console.log( replaceExceptChar("asdasd2323(*(&*/", "/") );
Upvotes: 0