Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we are using _ in this expression str.replace(/[\W_]/g, '').toLowerCase(); We could have used /[\W]/g also but why are we using underscore?

It is a javascript question.I was solving palindromes question 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;
 }
like image 526
Uzma Khan Avatar asked Oct 30 '15 13:10

Uzma Khan


1 Answers

The \W metacharacter is used to find a non-word character. A word character is a character from a-z, A-Z, 0-9, including the underscore character. This means that if you use [\W] and not [\W_]

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

your normalizedStr will still contain underscore after the replacement.

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

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

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

Also, instead of converting the string to array, reverse it and convert it back to string before comparison, better use a for loop to compare the arrays for much better performance (especially if the string is bigger):

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 should be first and the true statement must be outside the for loop, otherwise it will break the function after the first match and return inaccurate result.

Benchmark snippet here:

const stringLength = 100000;  // < < ADJUST THE STRING LENGTH HERE

const string = superString(stringLength);

console.log(`Random string length: ${string.length} symbols`);

benchMark(arraySplitReverseJoinMethod);
benchMark(forLoopComparisonMethod);

function arraySplitReverseJoinMethod(str) {
  return str == str.split('').reverse().join('');
}

function forLoopComparisonMethod(str) {
  let string = str.split('');
  
  for (var i = 0; i < string.length/2; i++) {
    if (string[i] !== string[string.length -1 -i]) {  
      return false;
    } 
  }

  return true;
}

function benchMark(func) {
  const start = +new Date();

  func(string);

  const end = +new Date();
  const total = end - start;

  console.log(`${func.name}: ${total} ms`);

  return `${func.name}: ${total} ms`;
}

function superString(n) {
  let superString = '';

  for (let i = 0; i < n; i++) {
    const randomString = Math.random().toString(36).substring(2, 12);

    superString = superString.concat(randomString);
  }

  return superString;
}
like image 143
krankuba Avatar answered Nov 15 '22 03:11

krankuba