REGEX - Highlight part over 19 chars

前端 未结 2 1703
生来不讨喜
生来不讨喜 2020-12-10 09:50

Hi,

I have some text inside div[contenteditable=\"true\"] and I should highlight (span.tooLong) part which goes over the 1

2条回答
  •  猫巷女王i
    2020-12-10 10:34

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

    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.

    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, "" + extra + "");
        $('#sample').html(newContent);
      });
    });
    

    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.

    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.

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

提交回复
热议问题