简体   繁体   English

如何避免重复以下替换代码?

[英]How to avoid repeating the following replace code?

This is the input: 这是输入:

[ 'markdown',
  [ 'para', '"a paragraph"' ],
  [ 'hr' ],
  [ 'para', '\'another paragraph\'' ],
  [ 'bulletlist', [ 'listitem', '"a list item"' ] ] ]

The following code loops through each element of the array. 以下代码循环遍历数组的每个元素。 If the elements is another array the code goes one depth further and applies replace , if not, it applies replace immediately (if I didn't have that if statement replace on an array would cause error. 如果元素是另一个数组,则代码会进一步深入并应用replace ,如果不是,它将立即应用replace (如果我不知道在数组上执行if replace会导致错误。

  for (i = 1; i < tree.length; i++) {
    var node = tree[i]
    var x = node.length - 1
    var y = node[x].length - 1

    if (Array.isArray(node[x])) {
      node[x] = node[x][y].replace(/"(?=\b)/g, '“')
                          .replace(/"(?!\b)/g, "”")
    } else {
      node[x] = node[x].replace(/"(?=\b)/g, '“')
                       .replace(/"(?!\b)/g, "”")
    }
  }

What bothers me is the duplication with replace . 困扰我的是与replace的重复。 How can I modify the code so I just do .replace(/"(?=\\b)/g, '“').replace(/"(?!\\b)/g, "”") once? 我该如何修改代码,以便只执行一次.replace(/"(?=\\b)/g, '“').replace(/"(?!\\b)/g, "”")一次?

Extract logic in a function: 提取函数中的逻辑:

   function replaceMe(element) {
        return element.replace(/"(?=\b)/g, '“')
                      .replace(/"(?!\b)/g, "”");
    }


...
  for (i = 1; i < tree.length; i++) {
    var node = tree[i]
    var x = node.length - 1
    var y = node[x].length - 1

    if (Array.isArray(node[x])) {
      node[x] = replaceMe(node[x][y]);
    } else {
      node[x] = replaceMe(node[x]);
    }
  }
...

use iteration, valid for N-dimensional array 使用迭代,对N维数组有效

function doWork(tree){
  for (i = 1; i < tree.length; i++) {
    var node = tree[i]
    var x = node.length - 1
    var y = node[x].length - 1

    if (Array.isArray(node[x])) {
      doWork(node[x]);
    } else {
      node[x] = node[x].replace(/"(?=\b)/g, '“')
                       .replace(/"(?!\b)/g, "”")
    }
  }
}

// use it
doWork(tree);

Sometimes two simple regex it's faster than one complex. 有时,两个简单的正则表达式比一个复杂的正则表达式快。

But you can try a different approach like this: 但是您可以尝试使用其他方法,例如:

var example_string = '"some_string"',
    regex = /"(.*?)"/g;

var result = example_string.replace(regex, "“$1”");

console.log(result); // “some_string”

``` ```

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM