Why do we use _ in this expression str.replace (/ [\ W _] / g, '') .toLowerCase (); We could use / [\ W] / g, but why do we use the underscore?

This is a javascript question. I solved the issue of palindromes on freecodecamp. Let me write the full code here:

function palindrome(str) { var normalizedStr = str.replace(/[\W_]/g, '').toLowerCase(); var reverseStr = normalizedStr.split('').reverse().join(''); return normalizedStr === reverseStr; } 
+5
source share
2 answers

The \ W meta-detector is used to search for a character without a word. The word character is the character from az, AZ, 0-9,, including the underscore . This means that if you use [\ W] and not [\ W _]

 var normalizedStr = str.replace(/[\W]/g, '').toLowerCase(); 

your normalizedStr will contain an underscore after replacement.

Since this call requires the removal of all non-alphanumeric characters (punctuation, spaces and characters), it will return unwanted results for any processed strings that include "_":

palindrome ("_ eye") - should return true, but instead it will be false;

palindrome ("0_0 (: / - \ :) 0-0") - should return true, but instead will be false;

In addition, instead of converting a string to an array, cancel it and convert it back to a string before comparison, it is better to use a loop to compare arrays for better performance (especially if the string is larger):

 function palindrome(str) { var clearString = str.toLowerCase().replace(/[^0-9a-z]/gi, '').split(''); for (var i = 0; i < clearString.length/2; i++) { if (clearString[i] !== clearString[clearString.length -1 -i]) { return false; } } return true; } 

Keep in mind that the false statement must be the first and the true statement must be outside the for loop , otherwise it will break the function after the first match and return an inaccurate result.

+7
source

\W matches any character without a word [^a-zA-Z0-9_]

_ letter symbol _

therefore, this regular expression will contain only letters and numbers in your string

+2
source

Source: https://habr.com/ru/post/1234866/


All Articles