[英]Regex to remove leading and trailing special characters and spaces from string
I'm trying to find a regex to remove all leading/trailing spaces as well as all leading/trailing special characters.我试图找到一个正则表达式来删除所有前导/尾随空格以及所有前导/尾随特殊字符。
If I have the string:如果我有字符串:
test = '~!#@$@ hello this is a #! test ^^#!^^ '
I'd like it to return as:我希望它返回为:
'hello this is a #! test'
So special characters and spaces in between the first and last letter are preserved, but all leading/trailing ones are cut out.因此保留了第一个和最后一个字母之间的特殊字符和空格,但所有前导/尾随字符都被删除。 Right now I have this:
现在我有这个:
test.replace(/[^a-zA-Z ]/g,"").replace(/^\s+|\s+$/g, "")
which returns:返回:
'hello this is a test'
so it is removing all special characters and leading/trailing spaces.所以它正在删除所有特殊字符和前导/尾随空格。 How can I preserve that "#?"
我怎样才能保留那个“#?” between "a" and "test"?
在“a”和“test”之间?
By using the unicode flag u
you can use the Unicode Categories for Letters \p{L}
and Numbers \p{N}
in a negative character class [^...]
.通过使用 unicode 标志
u
,您可以在负字符 class [^...]
中使用字母\p{L}
和数字\p{N}
的 Unicode类别。
And match them at the start ^
or |
并在开头匹配它们
^
或|
at the end $
to get anything that's not a letter or number and is trailing or leading.在最后
$
得到任何不是字母或数字的尾随或前导的东西。
Pattern:图案:
^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$
Test Snippet:测试片段:
let test = '~;#@$@ hello this is a #. test ^^#,^^ '; test = test.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu; ''); document.write('['+test+']');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.