简体   繁体   English

如何删除字符串开头和结尾的所有符号(如果有)?

[英]How do I remove all symbols from the beginning and end of a string, if any?

Keep only the alphabet and numbers. 仅保留字母和数字。

--I have a dog!!! should result in I have a dog 应该导致I have a dog

I have a dog. should result in I have a dog 应该导致I have a dog

尝试用此正则表达式替换:

/^[^a-z\d]*|[^a-z\d]*$/gi
s = "--I have a dog!!!"
s.replace(/^[^a-zA-Z\d]*(.*?)([^a-zA-Z\d])*$/, "$1")

Please note, that this will do exactly what you asked for. 请注意,这将完全满足您的要求。 It will remove non-alphanumeric characters only from the beginning and from the end of the string. 它将仅从字符串的开头和结尾删除非字母数字字符。 All non-alpha and non-digits in the middle of the string won't be removed. 字符串中间的所有非字母和非数字都不会被删除。

Just use regular expressions and replace 只需使用正则表达式并替换

'--I have a dog!!!'.replace(/[^a-zA-Z 0-9]*/g,''); // "I have a dog"

That will remove from every location of string any other characters than numbers, letters and spaces. 这将从字符串的每个位置删除数字,字母和空格以外的任何其他字符。

If you want explicitly remove from beginning and end only, then you will need something like this: 如果只想从开头和结尾显式删除,则将需要以下内容:

'--I have !!! a dog!!!'.replace(/^[^a-zA-Z 0-9]*|[^a-zA-Z 0-9]*$/g,''); // "I have !!! a dog"

Learn more regex at regular-expressions.info , there are JavaScript examples too. regular-expressions.info上了解更多正则表达式,也有JavaScript示例。

Try this: 尝试这个:

var x = '--I have a dog!!!';
x = x.replace(/[^0-9A-Za-z\s]/g, '');

// results in "I have a dog"

Use the Regex to solve this: 使用正则表达式解决此问题:

var s = '--I have a dog!!!';
s = s.replace(/^[^a-z\d]*|[^a-z\d]*$/gi, '');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从字符串的开头和结尾删除符号,除了某些符号? - How to remove symbols from beginning and end of a string, except certain symbols? 正则表达式删除所有<br /> javascript中字符串开头和结尾的标签 - Regex to remove all <br /> tags from beginning and end of a string in javascript 删除字符串开头和结尾的多个字符中的任何一个 - Remove any of multiple characters at beginning and end of string 从字符串中的单词的开头和结尾删除标点符号 - Remove punctuation from beginning and end of words in a string 从字符串的开头和结尾删除单引号 - Remove single quotes from beginning and end of string 如何仅从整个字符串的开头删除括号中的字符串? - How do I remove the string in brackets only from the beginning of the entire string? 使用jQuery或javascript从网页中存在的所有文本框的字符串开头和结尾删除空格 - Remove whitespace from beginning and end of string of all textbox present in a webpage using jQuery or javascript 如何生成不包含任何空格的正则表达式,甚至在字符串的开头或结尾也不包含任何空格 - How to generate Regular Expression that doesn't contain any white space at all and even at the beginning or the end of the string 如何从JavaScript数组项的开头删除“undefined”? - How do I remove “undefined” from the beginning of JavaScript array items? 去掉 <ul> 字符串开头和结尾的标签(JavaScript或PHP) - Remove <ul> tags from beginning and end of string (JavaScript or PHP)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM