admin管理员组文章数量:1194126
I have some strings that I want to clean up by removing all non-alphanumeric characters from the beginning and end.
It should work on these strings:
)&*@^#*^#&^%$text-is.clean,--^2*%#**)(#&^ --->> text-is.clean,--^2
-+~!@#$%,.-"^&[email protected],--^#*%#**)(#&^ --->> [email protected]
I have this regex, which removes them from the whole string:
val.replace(/[^a-zA-Z0-9]/g,'')
How would I change it to only remove from the beginning and end of string?
I have some strings that I want to clean up by removing all non-alphanumeric characters from the beginning and end.
It should work on these strings:
)&*@^#*^#&^%$text-is.clean,--^2*%#**)(#&^ --->> text-is.clean,--^2
-+~!@#$%,.-"^&[email protected],--^#*%#**)(#&^ --->> [email protected]
I have this regex, which removes them from the whole string:
val.replace(/[^a-zA-Z0-9]/g,'')
How would I change it to only remove from the beginning and end of string?
Share Improve this question asked Aug 15, 2013 at 10:23 Alexandru RAlexandru R 8,82316 gold badges67 silver badges103 bronze badges 1- No, it was a bad example, I fixed it. – Alexandru R Commented Aug 15, 2013 at 10:24
4 Answers
Reset to default 13Modify your current RegExp to specify the start or end of string with ^
or $
and make it greedy. You can then link the two together with an OR |
.
val.replace(/^[^a-zA-Z0-9]*|[^a-zA-Z0-9]*$/g, '');
This can be simplified to a-z
with i
flag for all letters and \d
for numbers
val.replace(/^[^a-z\d]*|[^a-z\d]*$/gi, '');
You need to use anchors - ^
and $
. And also, you would need a quantifier - *
:
val.replace(/^[^a-zA-Z0-9]*|[^a-zA-Z0-9]*$/g,'')
Use anchors to match the start and end of the string:
val.replace(/^[^A-Z0-9]+|[^A-Z0-9]+$/ig, '')
Use anchors ^
and $
to match positions before first character and after last character in the string.
val.replace(/(^[^A-Za-z0-9]*)|([^A-Za-z0-9]*$)/g, '');
You can also shorten your code using \W
which means non-alphanumeric character, shortcut for [^a-zA-Z0-9_]
in case you want to keep underscore as well.
val.replace(/(^\W*)|(\W*$)/g, '');
版权声明:本文标题:regex - How to trim all non-alphanumeric characters from start and end of a string in Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738458555a2087895.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论