0
string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');

string = string.replace(/[^a-zA-Z0-9]/g, '');

This is the code that I found online. I am little confused about it. How come first line of code "excludes" special characters whereas 2nd line only include those characters that are only in []. Both functions are "replace" then how come they are doing totally opposite work.

Ash
  • 261
  • 4
  • 16
  • 1
    It is a regular expression https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions – epascarello Apr 11 '17 at 23:39
  • https://regexper.com/#%2F%5B%5Ea-zA-Z0-9%5D%2Fg and https://regexper.com/#%2F%5B%26%5C%2F%5C%5C%23%2C%2B()%24~%25.'%22%3A*%3F%3C%3E%7B%7D%5D%2Fg – epascarello Apr 11 '17 at 23:41
  • Different arguments are passed to `.replace`. Is it so surprising that the return value of a function is different for different input? If you don't know about regular expression, have a look at http://regular-expressions.info/ to get started. – Felix Kling Apr 11 '17 at 23:41

2 Answers2

2

the first regular expression says: if you find any of these characters, replace them with nothing.

the second regular expression says: if you find any characters THAT AREN'T listed here, replace them with nothing.

[^xyz] matches anything but x, y or z. The key difference is the '^' which, when it is the first character in a [] means don't match!

Here's a good link that explains character classes and negated character classes.

Arthur Cinader
  • 1,547
  • 1
  • 12
  • 22
2

The reason is that the caret (^) has special meaning when it comes directly after an opening bracket. It means "not the following", so when it is used in a replace, it will replace everything except what is in those brackets.

For a far more eloquent explanation, see this SO answer

The first example does not have a caret after the opening bracket, so it will exclude anything inside those brackets.

Community
  • 1
  • 1
Daniel Bernsons
  • 650
  • 7
  • 20
  • Thank you for your explanation. I actually searched this but was not satisfied. Thanx for clearing it up. – Ash Apr 11 '17 at 23:51