【问题标题】:Taking a string and diving it into a array given an regex获取一个字符串并将其放入一个给定正则表达式的数组中
【发布时间】:2021-04-22 10:28:38
【问题描述】:

我有以下结构,要么是单个字符串数组 ['stufff sjktasjtjser ((matchthis))'],要么是嵌套数组中的相同结构 ['stufff', ['more stuff ((matchhere))'] , '((andanother))']; 我可以循环匹配括号中的所有正则表达式,甚至替换文本:

//after flattening the array lets take the first one, assume I am looping in the first element.
var matches = currentArrayElement.matchAll('fancyregex') //pretend I am matching the brackets
matchs.forEach(match=>currentArrayElement=currentArrayElement.replaceAll(match[0],'whatwhat'))
console.log(currentArrayElement)//'stufff sjktasjtjser whatwhat'
//but what I actually want is
// currentArrayElement = ['stufff sjktasjtjser','whatwhat'];

有谁知道我如何做到这一点?或者任何可以在嵌套数组中做到这一点的模板库?我有时需要输出一个字符串数组 ['tss'],有时需要输出一个带有对象 [{}] 的数组。

谢谢。

【问题讨论】:

  • 你能提供几个输入输出的例子吗?

标签: javascript arrays regex


【解决方案1】:

问题是我需要更改该索引中的数组而不是整个数组。

这是我当时所做的:

//after flattening the array lets take the first one, assume I am looping in the first element.
var matches = currentArrayElement.matchAll('fancyregex') //pretend I am matching the brackets
matches.forEach((match) => {
      currentArrayElement[i] = c.split(match[0]).flatMap(
        (value, index, array) => (array.length - 1 !== index
          ? [value, 'whatwhat',]
          : value),
      );
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    相关资源
    最近更新 更多