简体   繁体   English

删除随机符号之间的文本 - JavaScript

[英]Remove text between random symbols - JavaScript

I have this input text with a pattern * + [*]*[/*] + * :我有这个带有模式* + [*]*[/*] + *的输入文本:

Input: [tag]random text EXCLUDE[/tag] text here输入: [tag]random text EXCLUDE[/tag] text here

Output: text here Output: text here

Input: [tag_1]another random text EXCLUDE[/tag_1] another text here输入: [tag_1]another random text EXCLUDE[/tag_1] another text here

Output: another text here Output: another text here

Input: [tag_1]another random text EXCLUDE[/tag_1] another text here [tag_1] another random text EXCLUDE[/tag_1] text [tag_3]another random text EXCLUDE[/tag_3]输入: [tag_1]another random text EXCLUDE[/tag_1] another text here [tag_1] another random text EXCLUDE[/tag_1] text [tag_3]another random text EXCLUDE[/tag_3]

Output: another text here text Output: another text here text

What I want is to remove the text, between [*] and [/*] , like replacing it with ''.我想要的是删除[*][/*]之间的文本,比如用 '' 替换它。

The problem is that the symbols, between [] are random, but if there is an open [*] , there is and closed [/*] , without nesting.问题是[]之间的符号是随机的,但是如果有一个开放的[*] ,就有一个封闭的[/*] ,没有嵌套。

This should do the trick:这应该可以解决问题:

let OUTPUT = INPUT
    .split('[')
    .filter(s => s.indexOf(']') == -1 || s.startsWith('/'))
    .map(s => s
        .split(']')
        .reverse()[0])
    .join('')

The main point is, the text inside [] doesn't actually matter, all we need are the square brackets to act as "anchors".要点是,[] 中的文本实际上并不重要,我们只需要方括号作为“锚点”。

I tried and failed to write a concise step-by-step explanation... My suggestions is to copy-paste the code in a console, feed it some data and watch what comes out of each step, it's self-evident.我尝试并没有写出一个简明的分步解释......我的建议是将代码复制粘贴到控制台中,为其提供一些数据并观察每一步的结果,这是不言而喻的。

This looks like a nice job for regular expressions:对于正则表达式来说,这看起来不错:

 const theStrings = [ '[tag]random text EXCLUDE[/tag] text here', '[tag_1]another random text EXCLUDE[/tag_1] another text here', '[random]another random text EXCLUDE[/random] another text here', '[this]is not to be [/filtered] as they don\'t match', '[tag_1]another random text EXCLUDE[/tag_1] another text here [tag_1] another random text EXCLUDE[/tag_1] text [tag_3]another random text EXCLUDE[/tag_3]' ] let replaced = ''; let prev_len = 0; theStrings.forEach(str => { replaced = str; do { prev_len = replaced.length; replaced = replaced.replace(/\[(.*)\].*?\[\/\1\](.*)/,'$2') } while (replaced.length < prev_len); console.log("before:",str,"\nafter:", replaced) } )

https://regex101.com/r/cE6NZm/1 https://regex101.com/r/cE6NZm/1

basically it's capturing anything between [this] and [/this] (notice they are the same but the second one has to be preceded by a / ) and letting out that portion of the string基本上它捕获[this][/this]之间的任何内容(注意它们是相同的,但第二个必须以/开头)并放出字符串的那部分

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

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