【问题标题】:If array item includes string but does not include other string then remove string如果数组项包含字符串但不包含其他字符串,则删除字符串
【发布时间】:2020-02-14 02:34:12
【问题描述】:

我有一大块文本,我已经用新行分割了,所以数组中的每个项目都是一行文本。

我正在遍历这些行并试图检测一行包含</mark>但不包含<mark>的位置,如果满足此条件,则删除</mark>(因为它丢失了一个开始标签)。

final_formatted_log_split = logtext.split("\n");

for (i = 0, l = final_formatted_log_split.length; i < l; i++) {
  if (final_formatted_log_split[i].includes("<mark>") === false) {
    if (final_formatted_log_split[i].includes("</mark>") === true) {
      var removed_mark = final_formatted_log_split[i].replace("</mark>", "");
    }
  }
}

var final_formatted_log = final_formatted_log_split.join("\n");
console.log(final_formatted_log);

并且此控制台日志仍然包含在不包含

的文本中

为了超级清楚,预期的结果如下:

如果一行是这样的:

line of text here</mark>

然后它需要删除&lt;/mark&gt;,因为它不包含开口&lt;mark&gt;

我怀疑这与 === 错误有关,但根据我在网上阅读的内容,其他人如何使用 .includes 来查看某些内容是否“不包含”

【问题讨论】:

  • 同一行可以有多个&lt;mark&gt;s或嵌套的吗?
  • @CertainPerformance 尽管replace 函数也应该删除重复项...
  • OP- 你能给我们一个你的代码不起作用的文本行的例子吗?之前是什么,之后是什么?
  • @Gibor 不幸的是没有,如果您没有指定带有 g 标志的正则表达式,replace 函数只会替换第一次出现 - 请参阅第一个演示中的第二个变体: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 或在同一页面下:substr(模式)

标签: javascript


【解决方案1】:

你可以用简单的String.prototype.includes

const arr = [
  '<mark>1</mark>',
  '2</mark>',
  '3</mark></mark>',
  '<mark>4</mark>',
]

const replaceMark = (arr) => {
  return arr.map(e => {
    if (e.includes('</mark>') && !e.includes('<mark>')) e = e.replace(/\<\/mark\>/g, '')
    return e
  })
}

console.log('original:', arr)
console.log('replaced:', replaceMark(arr))

这个解决方案不能处理像&lt;mark&gt;text&lt;/mark&gt;&lt;/mark&gt;这样的复杂情况,只处理最基本的情况。

【讨论】:

    【解决方案2】:

    ===false 没有任何问题。它工作正常。要检查这个,你只需在 if 块中放一个 console.log

    你在这里做的是,你没有用修改过的替换数组值。所以替换这一行

    var removed_mark = final_formatted_log_split[i].replace("&lt;/mark&gt;", "");

    final_formatted_log_split[i] = final_formatted_log_split[i].replace("&lt;/mark&gt;", "");

    您可以使用一个 if 块而不是两个 if 块。

    var final_formatted_log_split = logtext.split("\n");;
    
    for (i = 0, l = final_formatted_log_split.length; i < l; i++) {
      if (!final_formatted_log_split[i].includes("<mark>") && final_formatted_log_split[i].includes("</mark>")) {
          final_formatted_log_split[i] = final_formatted_log_split[i].replace("</mark>", "");
      }
    }
    
    var final_formatted_log = final_formatted_log_split.join("\n");
    console.log(final_formatted_log);
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-09
      • 2018-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-30
      • 1970-01-01
      • 2017-06-06
      相关资源
      最近更新 更多