简体   繁体   English

如何突出显示与正则表达式匹配的部分

[英]How to highlight the portion matched with regex

I am trying to highlight (with red) the error portion of the input (thus the user can easily find out where and what the error is) and matching the error portion with regex. 我试图突出显示(用红色)输入的错误部分(因此用户可以轻松地找出错误的位置和原因),并将错误部分与正则表达式匹配。

I tried something like the following: (say I am accepting letters but not digits) 我尝试了以下操作:(例如,我接受字母,但不接受数字)

$("#myInputId")
    .filter(function() {
        return this.value.match(/[\d]/);
    })
    .addClass("error")

But the above code is highlighting the whole input, but not only the error portion. 但是上面的代码突出显示了整个输入,而不仅仅是错误部分。

I just put the following image to make what I say is more clear: 我只是把下面的图片放在我所说的更清楚:

在此处输入图片说明

NOTE : I am trying achieve this without adding any jQuery plugins for highlighting texts. 注意 :我试图在不添加任何jQuery插件来突出显示文本的情况下实现这一目标。

The filter function returns true because what is in this.value matches the required regex. 过滤器函数返回true,因为this.value中的内容与所需的正则表达式匹配。 Thus the whole element #myInputId is ok. 因此,整个元素#myInputId都可以。 And to this element you apply the error class. 然后将error类应用于此元素。

You need to apply the class only to the relevant portion. 您只需要将类应用于相关部分。 What you should probably do, is replace the found string within the #myInputId with the same string only enclosed in an error span. 您可能应该做的是#myInputId找到的字符串替换为仅包含在错误范围的相同字符串。

This: 这个:

<div id="myInputId">James1234</div>

Becomes this: 变成这个:

<div id="myInputId">James<span class="error">1234</span></div>

You can achieve this by using the found string, like this: 您可以使用找到的字符串来实现此目的,如下所示:

var newStr = wholeStr.replace(foundStr, '<span class="error">'+foundStr+'</span>');

I think this is because you are adding the class "error" to the element which has all the text "James1234" in it. 我认为这是因为您要向包含所有文本“ James1234”的元素添加“错误”类。

At the moment I think something like this is happening 目前,我认为这种情况正在发生

<p class="error">
    james1234
</p>

if it was free text and you did text replace and changed the html to something like this 如果它是自由文本,并且您进行了文本替换并将html更改为类似这样的内容

<p>
    james<span class="error"/>1234<span/>
</p>

so to achieve this I think you would need to do something like this 所以要实现这一点,我认为您需要做这样的事情

    var searchterm = '1234'
    value.replace(searchTerm, "<span class='error'/>" + searchterm + "<span/>");

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

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