[英]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.