[Solved] Textarea hashtag highlight is applied to the wrong position after the first line [closed]


The problem you’re facing here is that your regex is replacing newline characters with a space before the final replacement of newline characters by <br /> elements occurs.

As a result, in cases where your hashed string is preceded by a newline, the highlight will appear on the previous line, rather than correctly being placed on the same line as the hashed string.

A quick fix to this is to swap the last two string replacements, and add a space after the <br /> to avoid it being included in the hashed string:

$(document).ready(function(){
   $('#t').on('input keyup', function() {
       var str = $(this).val();       
       str = str.replace(/(<.+?>)/gi, '');
       str = str.replace(/(?:\r\n|\n\r|\r|\n)/g, '<br /> ');
       str = str.replace(/(?:\s|^)#([^0-9\W\s][a-zA-z0-9]*)/g, ' <b>#$1</b>');       
       $('#input').html(str);
   });
});

Here’s an updated JSFiddle to demonstrate. Hope this helps! Let me know if you have any questions.

2

solved Textarea hashtag highlight is applied to the wrong position after the first line [closed]