[英]Javascript remove all leading and trailing junk characters in a string
I have strings like 我有像
"&% , USEFUL DATA ^$^@&#!*, USEFUL DATA *%@^#,,, "
Need it cleaned like: 需要像这样清理它:
"USEFUL DATA ^$^@&#!*, USEFUL DATA"
Do we have any standard library function in Javascript to do that (We have it in python)? 我们在Javascript中有任何标准库函数可以做到这一点(在python中有)吗?
Ex: trim(str, "!@#$%^^&*(), ")
例如:
trim(str, "!@#$%^^&*(), ")
You can use: 您可以使用:
str = str.replace(/^\W+|\W+$/g, "");
\\W
will match all the non-word characters. \\W
将匹配所有非单词字符。
To remove specific character use character class: 要删除特定字符,请使用字符类:
str = str.replace(/^[@#$%^&*(), ]+|[@#$%^&*(), ]+$/g, "");
You can use a regex replace
: 您可以使用正则表达式
replace
:
var s = "&% , USEFUL DATA ^$^@&#!*, USEFUL DATA *%@^#,,, "; document.write(s.replace(/^\\W+|\\W+$/g, '') + "<br/>"); // or document.write(s.replace(/^[^\\w]+|[^\\w]+$/g, ''));
The pattern ^\\W+|\\W+$
will remove all "special" characters from both beginning and end of the string. 模式
^\\W+|\\W+$
将删除字符串开头和结尾的所有“特殊”字符。 Note that \\W
matches every character that is not in the [A-Za-z0-9_]
class, and \\w
matches those characters. 请注意,
\\W
匹配不在[A-Za-z0-9_]
类中的每个字符,并且\\w
匹配那些字符。 [^\\w]
is a negated character class where ^
means not , and then you can add more characters/shorthand classes that you want to keep. [^\\w]
是一个否定的字符类,其中^
表示不是 ,然后您可以添加更多要保留的字符/速记类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.