简体   繁体   English

jQuery 从字符串中删除特殊字符等

[英]jQuery remove special characters from string and more

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

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: replace(/[^a-z0-9\\s]/gi, '')会将字符串过滤为仅字母数字值,而replace(/[_\\s]/g, '-')将替换下划线和空格连字符:

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

Source for Regex: RegEx for Javascript to allow only alphanumeric Regex 的来源: RegEx for Javascript to allow only alphanumeric

Here is a demo: http://jsfiddle.net/vNfrk/这是一个演示: http : //jsfiddle.net/vNfrk/

假设“特殊”是指非单词字符,那么这很容易。

str = str.replace(/[_\W]+/g, "-")
str.toLowerCase().replace(/[\*\^\'\!]/g, '').split(' ').join('-')

Remove numbers, underscore, white-spaces and special characters from the string sentence.从字符串句子中删除数字、下划线、空格和特殊字符。

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

Demo演示

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

Since I can't comment on Jasper's answer, I'd like to point out a small bug in his solution:由于我无法评论 Jasper 的回答,我想指出他的解决方案中的一个小错误:

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

Remove/Replace all special chars in Jquery :删除/替换 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我的名字是 Ghanshyam,来自 Java 背景

Where g means Global其中 g 表示全局

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 "-"第一个正则表达式用空格删除特殊字符而不是从字符串中删除额外的空格,最后一个正则表达式用“-”替换空格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM