jQuery remove special characters from string and m

2020-02-16 07:04发布

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';

7条回答
Fickle 薄情
2楼-- · 2020-02-16 07:07

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, ""));

查看更多
时光不老,我们不散
3楼-- · 2020-02-16 07:17

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 it

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

result: My name is Ghanshyam and from java background

Where g means Global @Thanks

查看更多
Anthone
4楼-- · 2020-02-16 07:18

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/

查看更多
乱世女痞
5楼-- · 2020-02-16 07:19

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, '');
查看更多
forever°为你锁心
6楼-- · 2020-02-16 07:25

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

str = str.replace(/[_\W]+/g, "-")
查看更多
狗以群分
7楼-- · 2020-02-16 07:26

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

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

Demo

查看更多
登录 后发表回答