简体   繁体   中英

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)?

Ex: trim(str, "!@#$%^^&*(), ")

You can use:

str = str.replace(/^\W+|\W+$/g, "");

\\W will match all the non-word characters.

RegEx Demo

To remove specific character use character class:

str = str.replace(/^[@#$%^&*(), ]+|[@#$%^&*(), ]+$/g, "");

You can use a regex 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. Note that \\W matches every character that is not in the [A-Za-z0-9_] class, and \\w matches those characters. [^\\w] is a negated character class where ^ means not , and then you can add more characters/shorthand classes that you want to keep.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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