REGEX - 突出显示超过19个字符的部分 [英] REGEX - Highlight part over 19 chars

查看:101
本文介绍了REGEX - 突出显示超过19个字符的部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

我在 div [contenteditable =true]中有一些文字我应该突出显示( span.tooLong )部分超过19个字符的限制。 div 中的内容可能包含HTML标签或实体,而在计数到19时应该忽略这些内容。

I have some text inside div[contenteditable="true"] and I should highlight (span.tooLong) part which goes over the 19 character limit. Content in div may have HTML tags or entities and those should be ignored when counting to 19.

Twitter有类似的方式突出太长的推文:

Twitter has similar way to highlight too long tweet:

示例:


  • 这是文本这是文本

  • 这也是长文本这也是太浅了< span class =tooLong> ng text< / span>

  • 此< b>文本< / b>已经< i>格式化< / i>使用HTML 此< b>文本< / b>已经< span class =tooLong>< i>格式化< / i>使用HTML< / span>

  • This is textThis is text
  • This is just too long textThis is just too lo<span class="tooLong">ng text</span>
  • This <b>text</b> has been <i>formatted</i> with HTMLThis <b>text</b> has been <span class="tooLong"><i>formatted</i> with HTML</span>

如何在JavaScript中实现? >

How can I implement this in JavaScript?

(我想尽可能使用正则表达式)

(I want to use regular expressions as much as possible)

推荐答案

好的,这里有一些我认为可以为你工作的代码,或至少让你开始。

Okay... here's some code that I think will work for you, or at least get your started.

基本上,正则表达式你需要找到一切这是19个字符:

Basically, the regex you need to find everything over 19 characters is this:

var extra = content.match(/.{19}(.*)/)[1];

所以,我把一个样本文件放在一起,你可以如何使用这个。

So, I put together a sample document of how you might use this.

查看 演​​示

Take a look at the DEMO.

这是我正在使用的Javascript(我在这里使用jQuery的定位器,但这可以很容易地被修改为使用直接的Javascript ...我只是喜欢jQuery的东西,像这样) ...

Here's the Javascript I'm using (I'm using jQuery for the locators here, but this can easily be modified to use straight Javascript... I just prefer jQuery for stuff like this)...

$(document).ready(function() {
  $('#myDiv').keyup(function() {
    var content = $('#myDiv').html();
    var extra = content.match(/.{19}(.*)/)[1];

    $('#extra').html(extra);

    var newContent = content.replace(extra, "<span class='highlight'>" + extra + "</span>");
    $('#sample').html(newContent);
  });
});

基本上,我有三个DIV设置。一个为您输入您的文本。一个显示字符超过19个字符的限制。另外一个是显示如何突出显示额外的字符。

Basically, I have three DIVs setup. One for you to enter your text. One to show what characters are over the 19 character limit. And one to show how you might highlight the extra characters.

我的代码示例不检查HTML标签,因为有太多的尝试和处理...但是应该给你一个很好的起点,这可能如何工作。

My code sample does not check for html tags, as there are too many to try and handle... but should give you a great starting point as to how this might work.

注意:您可以查看使用此链接编写的完整代码: http://jsbin.com/OnAxULu/1/edit

NOTE: you can view the complete code I wrote using this link: http://jsbin.com/OnAxULu/1/edit

这篇关于REGEX - 突出显示超过19个字符的部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆