javascript 为什么我们在这个表达式中使用 _ str.replace(/[\W_]/g, '').toLowerCase(); 我们也可以使用 /[\W]/g 但为什么我们使用下划线?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33436807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:28:23  来源:igfitidea点击:

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?

javascriptalgorithm

提问by Uzma Khan

It is a javascript question.I was solving palindromes question on freecodecamp.Let me write the full code here:

这是一个javascript问题。我在freecodecamp上解决回文问题。让我在这里写完整的代码:

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

回答by krankuba

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

\ W元字符用于查找非单词字符。单词字符是 az、AZ、0-9 中字符,包括下划线字符。这意味着如果你使用 [\W] 而不是 [\W_]

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

your normalizedStr will still contain underscoreafter the replacement.

替换后,您的 normalizedStr 仍将包含下划线

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;

palindrome("_eye") -- 应该返回真,但它会是假的;

palindrome("0_0 (: /-\ :) 0-0") -- 应该返回true,但会返回false;

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 arraysfor much better performance (especially if the string is bigger):

此外,不要将字符串转换为数组,而是在比较之前将其反转并将其转换回字符串,最好使用for 循环来比较数组以获得更好的性能(尤其是在字符串较大的情况下):

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

请记住,false语句应该在前面true语句必须在 for 循环之外,否则会在第一次匹配后破坏函数并返回不准确的结果。

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;
}

回答by Ziki

\Wmatch any non-word character [^a-zA-Z0-9_]

\W匹配任何非单词字符 [^a-zA-Z0-9_]

_the literal character _

_文字字符 _

so this regex will keep in your string only letters and numbers

所以这个正则表达式只会在你的字符串中保留字母和数字