Wrap the word in the gap when clicked, even if next to the punctuation while maintaining the punctuation (javascript)

This question is based on the answer provided in How to wrap a word in a range on a user click in javascript .

In my example, the user can double-click on any word to wrap it in a span, but b / c is based on space breaks, it will not work if the word is followed by punctuation.

HTML:

<div class="color-coding">
  <span class="orange color-coding">Hello world this is some text.</span>
  <br>
  <span class="orange color-coding">Here is some more!</span>
</div>

JS:

jQuery(document).ready(function($) {

$('.color-coding').dblclick(function(e) {

var range = window.getSelection() || document.getSelection() || document.selection.createRange();
var sword = $.trim(range.toString());
if(sword.length)
{

  var newWord = "<span class='highlight'>"+sword+"</span>";

  $(this).each(function(){
      $(this).html(function( _, html ) {
    return html.split(/\s+/).map(function( word ) {
      return word === sword ? newWord : word;
    }).join(' ');
  });
  });
}
range.collapse();
e.stopPropagation();
});

});

I could add the detection of punctuation for separation, but this of course will remove the punctuation, and I need to save it, so using the following will not meet my needs:

html.split(/\s+|[.,-\/#!$%\^&\*;:{}=\-_`~()]/)

Fiddle: http://jsfiddle.net/b11nxk92/3/

+4
1

ExecCommand

:

if(sword.length) {
    this.setAttribute('contenteditable','true');
    document.execCommand("insertHTML", false, "<span class='highlight'>"+sword+"</span>");
    this.removeAttribute('contenteditable');
}

, , html-. : https://msdn.microsoft.com/en-us/library/hh801231(v=vs.85).aspx#inserthtml https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

Fiddle: http://jsfiddle.net/b11nxk92/6/

RegExp

, RegExp, .

if (sword.length) {

    $(this).each(function(){
        $(this).html(function( _, html ) {
            return html.replace(
                new RegExp("([^\\w]|^)("+sword+")([^\\w]|$)","g"),
                "$1<span class='highlight'>$2</span>$3"
            );
        });
    });
}

split, join ( ) + ( ) + ( ), $ , .

Fiddle: http://jsfiddle.net/b11nxk92/4/

0

Source: https://habr.com/ru/post/1610596/


All Articles