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
Add a comment  | 

4 Answers 4

Reset to default 13

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

本文标签: regexHow to trim all nonalphanumeric characters from start and end of a string in JavascriptStack Overflow