javascript - Textarea hashtag highlight is applied to the wrong position after the first line -
when going newline , starting hashtag there beginning of line, highlighter applying color previous line.
<style> #input{ color: transparent; } #input b{ text-decoration: none; color: transparent; background-color: #9aceff; font-weight: normal; } #t{ background-color: transparent; } </style>
<textarea id="t" style="width: 342px; height: 92px; resize: none; position: absolute; z-index: 1; border: 1px solid #212;font-family: arial; padding: 20px; margin: 0; font-size: 12px;"> </textarea> <div style="width: 300px; height: 50px; border: 1px solid #212; font-family: arial; padding: 20px; position: absolute; z-index: 0; margin: 0; font-size: 12px;" id="input"> </div>
<script> $(document).ready(function(){ $('#t').on('input keyup', function() { var str = $(this).val(); str = str.replace(/(<.+?>)/gi, ''); str = str.replace(/(?:\s|^)#([^0-9\w\s][a-za-z0-9]*)/g, ' <b>#$1</b>'); str = str.replace(/(?:\r\n|\n\r|\r|\n)/g, '<br />'); $('#input').html(str); }); }); </script>
here jsfiddle code.
the problem you're facing here regex replacing newline characters space before final replacement of newline characters <br />
elements occurs.
as result, in cases hashed string preceded newline, highlight appear on previous line, rather correctly being placed on same line hashed string.
a quick fix swap last 2 string replacements, , add space after <br />
avoid being included in 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 updated jsfiddle demonstrate. hope helps! let me know if have questions.
Comments
Post a Comment