Say I have var string1 = "Hello"
and string2 = "Hello"
How can I compare these two and ignore the capitals and the punctuation in javascript?
Asked
Active
Viewed 66 times
1

Matthew Parks Jr
- 23
- 7
-
1I think you're looking for something like [edit distance](https://en.wikipedia.org/wiki/Edit_distance). – Ted Hopp Mar 01 '17 at 19:04
1 Answers
2
Try this:
Use String.toLowerCase()
to lowercase a string. To remove punctuation, see this post: How can I strip all punctuation from a string in JavaScript using regex?
Then compare with the ===
operator. For example:
var string1 = "Hello";
var string2 = "Hello";
string1 = string1.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"");
string2 = string2.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"");
if (string1.toLowerCase() === string2.toLowerCase()) {
// Do something
}
-
Or `.replace(/[^a-z]/gi, "");`. And where is the semicolons `;`? – ibrahim mahrir Mar 01 '17 at 19:07
-
-
@ibrahimmahrir Also you aren’t accounting for capitals and numbers with that regex – Hum4n01d Mar 01 '17 at 19:09
-
Just a word of advice: **ALWAYS USE THE FREAKING SEMICOLONS OR ONE DAY YOU'LL REGRET IT**! – ibrahim mahrir Mar 01 '17 at 19:09
-
I don't think numbers are important and for the lower/upper case thing you can use the `i` modifier! – ibrahim mahrir Mar 01 '17 at 19:10