简体   繁体   English

Javascript删除字符串中所有开头和结尾的垃圾字符

[英]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将匹配所有非单词字符。

RegEx Demo 正则演示

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.

相关问题 正则表达式删除所有前导和尾随特殊字符? - Regex remove all leading and trailing special characters? 正则表达式从字符串中删除前导和尾随特殊字符和空格 - Regex to remove leading and trailing special characters and spaces from string 使用特定的前导和尾随字符拆分JavaScript字符 - Split on javascript character with specific leading and trailing characters 从字符串中删除前导零和尾随零 - Remove leading and trailing zeros from a string 使用 JavaScript 从数组中的字符串中删除所有字母字符和前导零 - Remove all alphabetical characters and leading zeros from strings in an array with JavaScript Javascript 从多行字符串中删除前导和尾随空格,并用逗号替换其余的空格块 - Javascript remove leading and trailing spaces from multiline string and replace the rest of whitespace chunks with commas Javascript拆分了一个字符串并删除了前导0 - Javascript split a string and remove leading 0 从字符串javascript中删除所有字符 - Remove all characters from string javascript 编写一个程序以在不使用内置方法的情况下从 JavaScript 中的给定字符串中修剪前导、尾随和额外的空白字符? - Write a program to trim both leading, trailing and extra whitespace characters from given string in JavaScript without using inbuilt methods? 如何从给定的 html 字符串中删除前导和尾随空格? - How to remove leading and trailing white spaces from a given html string?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM