【问题标题】:JavaScript get the text before the matchJavaScript 获取匹配前的文本
【发布时间】:2021-08-27 02:20:57
【问题描述】:

我怎样才能在 等号 (= ) 使用regex:

<p> target="" the-target="" the-other-target="" </p>
  • 等号是用HTML代码编写的:&amp;#61;
  • 大约有 9-10 个&lt;p&gt;&lt;/p&gt; 与不同的targets 类似。
  • 使用单词target 就是一个例子。

编辑:

  • 我必须使用下面的代码原样
    存储regex 的变量regexTarget 将与更多类似的变量一起添加到array,并循环检查它们。

  • 我也会使用replace

代码:

//var regexTarget = / &#61 /g;

$(".line").each(function(){
    if($(this).html().match(regexTarget)){
        // $(this).html() = $(this).html().replace(regexTarget, "");
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p class="line">target&#61"" the-target&#61"" the-other-target&#61""</p>
<p class="line">just-a-target&#61"" target&#61"" not-targeted&#61""</p>

【问题讨论】:

  • 您的预期结果是什么?
  • 您的编辑毫无意义 - 您使用该代码吗?那么,如果您不能更改代码,那么问题的意义何在?此外,该代码很糟糕(例如$(this).html() = 就是错误的)。请在edit 中包含您的预期结果。

标签: javascript html jquery regex


【解决方案1】:

给你

let str = 'target&#61"" the-target&#61"" the-other-target&#61""';

let result = [...str.matchAll(/(?:([\w-]*)[&#0-9]+)/g)].map(i => i[1])

console.log(result);

【讨论】:

  • 正如我在上面的问题中提到的,target 这个词就是一个例子,重点是得到等号之前的内容。
  • 完全正确,但请不要&amp;#61... 怎么样?
  • 已更新,请立即查看
【解决方案2】:

你可以使用正则表达式

/[\W]+([-\w]+)&#61/

const str = `<p class="line">target&#61"" the-target&#61"" the-other-target&#61""</p>
<p class="line">just-a-target&#61"" target&#61"" not-targeted&#61""</p>`;

const result = [...str.matchAll(/[\W]+([-\w]+)&#61/g)].map((arr) => arr[1]);
console.log(result);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 1970-01-01
    • 2012-05-01
    • 1970-01-01
    • 2022-11-02
    相关资源
    最近更新 更多