How to highlight a part of text in textarea

女生的网名这么多〃 提交于 2019-11-30 11:35:32

without wrapping a tag around the specific words, you cannot highlight it (or as i said, at least I have no idea how to). but if there is no problem with wrapping tags, you should use regEx.

for words starting with @ :

replace(/@([^ ]+)/g, '<span class="atsign">@$1</span>');

and for the words starting with # :

status.replace(/#([^ ]+)/g, '<span class="hashtag">#$1</span>');

check this fiddle

EDIT: you can replace

var status = 'I tweeted something #one #two @three @four';

with

var status = $('#phrase').text();
Abhishek Kargawal

Use setSelectionRange method on that text

Sample code:

<body>
    <section>
        <textarea id="textarea"></textarea>
        <button id="hgh">Hightlight @twiiter</button>
    </section>

    <script>

        window.onload = function () {

            var textarea = document.getElementById("textarea");
            var checkError = document.getElementById("hgh");

            checkError.addEventListener("click", function () {

                var index = textarea.innerText.indexOf("@twitter");
                if( index >= 0)
                    textarea.setSelectionRange(index, index + 8);
            });
        }

    </script>
</body>

I came here looking for an answer where I could highlight certain words in the textarea. Did'nt find an answer in this thread. So, adding how I did it:

For this example, you would do something like:

  1. Download and include scripts from here: http://garysieling.github.io/jquery-highlighttextarea/index.html

  2. And use this:

    <script>
    $('textarea').highlightTextarea({
     words: ['@twitter', '@twitpic'],
     id: 'demoCustom',
     caseSensitive: false
     // or a regular expression like -> words: ['@([^ ]+)']
    });
    </script>
    
    <style>
     #demoCustom mark {
      padding:0 3px;
      margin:-1px -4px;
      border-radius:0.5em;
      border:1px solid pink;
     }
    </style>
    

More Examples: http://garysieling.github.io/jquery-highlighttextarea/examples.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!