【问题标题】:Is there a better way to clean a string?有没有更好的方法来清理字符串?
【发布时间】:2022-01-06 04:37:13
【问题描述】:

目前,这是我的代码。

function clean_string(raw_string) {
    A =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 1234567890".split(
            ""
        );
    var cleaned_string = raw_string.toLowerCase();
    for (i = 0; i < cleaned_string.length; i++) {
        if (!A.includes(cleaned_string[i])) {
            cleaned_string = setCharAt(cleaned_string, i, " ");
        }
    }
    cleaned_string = cleaned_string.replace(/\s\s+/g, " ");

    return cleaned_string;
}

function setCharAt(str, index, chr) {
    if (index > str.length - 1) return str;
    return str.substring(0, index) + chr + str.substring(index + 1);
}

我不知道正则表达式,使用正则表达式可能会更容易。这是我想做的:

输入:Hello, David World 123!

输出:hello david world 123

.

输入:hELlo., &lt;&gt;;dAVId world .;- 123

输出:hello david world 123

.

输入: He.llo David, w!orld 123#

输出:he llo david w orld 123

.

基本上我想要做的是用空格替换除 a-z0-9 之外的任何内容,然后删除双空格。换句话说,我的结果中只需要 a-z0-9。我该怎么做?

附:该代码有效,但我认为它看起来很糟糕而且效率很低。

编辑:对不起,我的意思是我的输出中只需要小写字母。我很笨。

【问题讨论】:

  • 您说您希望在输出中允许使用大写字母,但是,在所有提供的示例中,大写字符都替换为小写字符。你能澄清一下吗?
  • @fubar 抱歉,我很笨。我解决了我的问题。我只想要小写字母。谢谢!

标签: javascript regex string trim


【解决方案1】:

一个简单的解决方案是将所有字符转换为小写,将任何不是 a-z、0-9 或空格的字符替换为空格字符,然后将多个空格字符替换为单个空格字符。

function sanitize(input) {
    return input
      .toLowerCase()
      .replace(/([^a-z\d\s]+)/g, ' ')
      .replace(/(\s+)/g, ' ');
}

console.log(sanitize('Hello, David World 123!'));
console.log(sanitize('hELlo.,     <>;dAVId  world  .;- 123'));
console.log(sanitize('He.llo     David,   w!orld 123#'));

【讨论】:

  • 为什么不直接删除有问题的字母,即用空字符串替换它们?那么要删除的多余空间就更少了。
  • @danielkullmann 这将使He.llo 返回hello 而不是he llo,这是我不想要的。
【解决方案2】:

这是使用正则表达式回调的一种方法:

var inputs = ["Hello, David World 123!", "hELlo.,     <>;dAVId  world  .;- 123", "He.llo     David,   w!orld 123#"];
for (var i=0; i < inputs.length; ++i) {
    var input = inputs[i];
    input = input.replace(/\w+/g, x => x.toLowerCase())
                 .replace(/[^\w_]+/g, " ");
    console.log(input);
}

这里的策略是做两个正则表达式替换。第一个查找输入中的所有单词并将它们转换为小写。第二个然后去除所有非单词字符和空格,包括下划线,并替换为单个空格。

【讨论】:

    【解决方案3】:

    一个简单的正则表达式来替换非字母数字字符,然后另一个来删除一行中的多个空格应该可以解决问题。

    const clean = (input) => {
      const alphanumeric = input.replace(/[^a-zA-Z0-9]/g, ' ')
      const spaceless = alphanumeric.replace(/\s{2,}/g, ' ')
      
      console.log(spaceless.toLowerCase())
      return spaceless.toLowerCase()
    }
    
    clean("Hello, David World 123!")
    clean("hELlo.,     <>;dAVId  world  .;- 123")
    clean("He.llo     David,   w!orld 123#   ")

    当然,函数可以简写为

    const clean = (input) => {
      return input.replace(/[^a-zA-Z0-9]/g, ' ').
                   replace(/\s{2,}/g, ' ').
                   toLowerCase()
    }
    

    正则表达式解释

    [^a-zA-Z0-9]: 匹配任何与 a-zA-Z0-9 不匹配的东西(任何非字母数字) \s{2,}:匹配连续出现两次或多次的空格

    【讨论】:

      【解决方案4】:

      您可以使用单个替换调用,或者仅将大写字符小写,或者将 1 个或多个非单词字符替换为单个空格。

      要区分替换和小写,您可以在正则表达式中使用捕获组并在回调函数中检查该组。

      如果匹配组 1,则有 1 个或多个大写字符 A-Z。

      [
        "Hello, David World 123!",
        "hELlo.,     <>;dAVId  world  .;- 123",
        "He.llo     David,   w!orld 123#"
      ].forEach(s =>
        console.log(
          s.replace(/([A-Z]+)|[^\w_]+/g, (_, g1) => g1 ? g1.toLowerCase() : ' ')
        )
      )

      【讨论】:

        猜你喜欢
        • 2012-12-28
        • 2011-01-01
        • 2016-07-21
        • 1970-01-01
        • 2014-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多