0

Why I am asking this: There are many questions similar to this one, but none of them are having a satisfactory answer.

Question:

It seems like, using Regular expression in a content editable HTML element for replacing specified string badly disturbs user's experience with caret positioning

What happens after using Ragex:

1:'Enter key'(earlier which was able to add line break) will stop working.

2:During any manual edit, caret assumes initial position (which is beginning of the editable HTML element).

So far the answers that I was able to find, have bugs!

My snippet with contenteditable="true" HTML element

```
<!DOCTYPE html>
<html>
<head>
<title>Experiment</title>
       <script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<meta name="viewport" width="device width, initial-scale=1.0">
<style>
#spanone{
    color:red;
    }
    #spantwo{
        color:yellow;
        }
</style>
</head>
<body style="background:royalblue;">
<p id="inp" contenteditable="true" style="height:90vh; width:90vw; background:black; color:white; font-weight:bold;">
{This} [is] {HTML} [rendered], {replaced string} [using ragex]! edit me!
</p>
 <script>
                $(function(){
                    $("#inp").on("input" , function(){
                        var str = $("#inp").text();
                        var new_str = str.replace(/(\[(?:[\w\s]*)*\])/g, function(match){
                            return match.replace(/(\w+)/g, '<span id="spanone">$1</span>');
                            });
                            var result = new_str.replace(/(\{(?:[\w\s]*)*\})/g, function(match){
                            return match.replace(/(\w+)/g, '<span id="spantwo">$1</span>');
                            });
                            $("#inp").html(result);
                            });
                            });
                            </script>
</body>
</html>
Alfha
  • 117
  • 9
  • Check [Modify text in a contenteditable div without resetting the caret (cursor) position](https://stackoverflow.com/questions/24845254/modify-text-in-a-contenteditable-div-without-resetting-the-caret-cursor-positi) – Wiktor Stribiżew Jun 23 '20 at 09:16
  • Don't you see bug? Enter key is not functioning properly, and after using enter sometimes text is added to the same line and then deletion of string is adding more string to it!... – Alfha Jun 23 '20 at 09:23
  • Also if you have any idea to render HTML element(using regex) inside textarea without compromising caret positioning, then please tell, that can also help me. – Alfha Jun 23 '20 at 09:27

0 Answers0