简体   繁体   English

删除所有特殊的连续字符

[英]Remove all special consecutive characters

Hopefully a simple one but I can't find any exact thread on SO for this particular instance:希望是一个简单的,但我找不到关于这个特定实例的任何确切线程:

If I have a string with multiple special characters in a row ie 'this-is--a---string' I want to remove all duplicate non alphanumeric characters with regex so it would end up as 'this-is-a-string'如果我有一个连续包含多个特殊字符的字符串,即'this-is--a---string'我想用正则表达式删除所有重复的非字母数字字符,所以它最终会成为'this-is-a-string'

The closest i've found is .replace(/(.)\1+/g, '$1') but this removes duplicate letters rather than just special characters.我找到的最接近的是.replace(/(.)\1+/g, '$1')但这会删除重复的字母而不仅仅是特殊字符。

On a side note if anyone knows how to remove any non alphanumeric characters from the end of a string with regex then that would be really useful too!附带说明一下,如果有人知道如何使用正则表达式从字符串末尾删除任何非字母数字字符,那也将非常有用!

Thanks in advance!提前致谢!

Since you want to collapse only repeated non alphanumeric characters, it should be enough to change your regex replacing the .由于您只想折叠重复的非字母数字字符,因此更改正则表达式替换. character class with something that will negate the alphanumeric group [^a-zA-Z0-9] .字符 class 与将否定字母数字组[^a-zA-Z0-9]东西。

 subject = "a---------------bbbbbb6times_______@@@@@@"; var myregexp = /([^a-zA-Z0-9])\1+/mg; result = subject.replace(myregexp, "$1"); console.log(result);

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

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