简体   繁体   中英

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. should result in 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.

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, '');

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