Trying to replace the string on the fly is the best way?

I am trying to replace some text "on the fly", surrounding it with a span.

Example:

A person prints when they type the word "back" and his space after it, he makes the whole sentence or line with this word in it bold.

Right now I have a CSS class setting for it, and I'm trying to include it in a range, but I'm not sure if this works ... it also resets something new at any time, so the cursor goes back to the beginning, and that doesn't allow me move forward.

Here is what I still have (my regex is wrong too):

function replace(e) {
  if (e.keyCode == 13) {
    element = document.getElementById("script");
    rg = /^INT/;
    element.innerHTML = element.innerHTML.replace(
      rg,
      '<span id="bold">$1</span>'
    );
  };
};
<div contenteditable="true" id="script" style="width: 100%; height: 500px; border: 1px solid black;" onkeydown="replace(event)">
  Replace
</div>
Run code
+4
source share
2 answers

@Mouser, regEx INT .

. RegEx . .

function replace(e) {
  if (e.keyCode == 13) {
    element = document.getElementById("script");
    var _str = element.innerHTML.trim("")
    rg = /INT/;
    element.innerHTML = _str.replace(
      rg,
      function($1) {
        console.log($1)
          return '<h1><span id="bold">' + $1 + '</span></h1>'
      } 
    );

    //Set cursor position
    var range = document.createRange()
    var _lastDom = element.childNodes[element.childNodes.length - 1];
    var end = '';
    if(_lastDom && _lastDom.innerHTML == undefined) {
        end = _lastDom.length
    } else {
        _lastDom
        end = 1
    }
    range.setStart(_lastDom,end)
    range.setEnd(_lastDom,end)
    sel = document.getSelection()
    sel.removeAllRanges()
    sel.addRange(range)
  };
};
+1

, , -

var thepara=document.getElementById('thepara').innerHTML;

document.getElementById('thetext').addEventListener('keyup',function(e){
 var thetext=this.value;
 var thelength=this.value.length;
 
  var thestart=thepara.indexOf(thetext);
  var found=thepara.substr(thestart,thelength);
  if(found != "n" ){
    var newstring="<span class='bolded'>"+found+"</span>";
      document.getElementById('thepara').innerHTML=thepara.replace(found,newstring);
  }
  });
.bolded{font-weight:bold;}
<input type="text" id="thetext" />
<div id="thepara">It was a nice sunny day in the suburbs of South East London</div>
0

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


All Articles