Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 536597
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T09:50:20+00:00 2026-05-13T09:50:20+00:00

How can I replace the selected text with another text using PURE javascript, in

  • 0

How can I replace the selected text with another text using PURE javascript, in Firefox?

This I use to get the selection:

var sel = this.getSelection();
var range = sel.getRangeAt(0);

And also this important issue:
I want to keep the original format of characters (of course the new string will have the right format )
The selection can be done “cross-elements” (by this I mean that the selection can contain some text from one element like div or table and some text from another elements).

example, the document:

<div>
 this is a test
</div>
<div>
<b>still a test</b>
</div>
 <table style="width:100%;">
        <tr>
            <td>
                another word</td>
            <td>
                stackoverflow</td>
        </tr>
        <tr>
            <td>
                bump</td>
            <td>
               </td>
        </tr>
    </table>

the user select the following text (via one selection):

his is a test still a test anot

So now I want to replace the text keeping the format, for instance replace every thing with new string =

XXX XX X XXXX XXXXX X XXXX XXXX

Final document (after replace) will be:

<div>
 tXXX XX X XXXX
</div>
<div>
<b>XXXXX X XXXX</b>
</div>
 <table style="width:100%;">
        <tr>
            <td>
                XXXXher word</td>
            <td>
                stackoverflow</td>
        </tr>
        <tr>
            <td>
                bump</td>
            <td>
               </td>
        </tr>
    </table>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T09:50:20+00:00Added an answer on May 13, 2026 at 9:50 am

    Wooove, that was a pitty!

    Javascript

    var sel, range, nodevalue, startFound, stop;
    
    function goThroughElements(el){
        // If el is the start node, set startFound to true
        if(el.isSameNode(range.startContainer)) startFound = true;
        
        if(startFound){
            // If this is the start node, replace the text like this: abcd[ef gh] --> abcdxx xx
            if(el.isSameNode(range.startContainer)){
                // \w stands for a word character
                nodevalue = el.nodeValue.substring(range.startOffset).replace(/\w/g, 'x');
                el.nodeValue = el.nodeValue.substring(0, range.startOffset) + nodevalue;
                
            }
    
            // If this is the end node, replace the value like this: [abc def]gh ij -> xxx xxxgh ij
            else if(el.isSameNode(range.endContainer)){
                nodevalue = el.nodeValue.substring(0,range.endOffset).replace(/\w/g, 'x');
                el.nodeValue = nodevalue + el.nodeValue.substring(range.endOffset);
                
                // Now we can stop
                stop = true;
            }
            
            // If this is just a text node, replace the value by xxxx
            else if(el.nodeType == 3){
                el.nodeValue = el.nodeValue.replace(/\w/g, 'x')
            }
        }
        
        // Loop trough el's brothers
        while(el){
            // Stop if we need to
            if(stop) return;
            
            // If this element has child nodes, call this function again with the first child node
            if(el.hasChildNodes()){
                goThroughElements(el.childNodes[0]);
            }
            
            // Jump to el's brother, or quit the loop
            if(el.nextSibling)
                el = el.nextSibling;
            else
                break;
        }
        
    }
        
    $(document).ready(function() {
        $(this).mouseup(function(){
            // Get the selection
            sel = window.getSelection();
            range = sel.getRangeAt(0);
            
            // Stop must be false if the last selected text node isn't found, startFound must be false when the start isn't found
            stop = false; startFound = false;
            
            if(range.collapsed == false){
                // Check if the selection takes place inside one text node element
                if(range.startContainer.isSameNode(range.endContainer)){
                    // ab[cdefg]h  -> aaxxxxxh
                    nodevalue = range.startContainer.nodeValue;
                    range.startContainer.nodeValue = nodevalue.substring(0, range.startOffset) + nodevalue.substring(range.startOffset, range.endOffset).replace(/\w/g, 'x') + nodevalue.substring(range.endOffset);
                } else {    
                    // If the start node of the selection isn't the same as the end node, loop through all elements
                    goThroughElements(range.commonAncestorContainer.childNodes[0]);
                }
                // Collapse selection.
                range.collapse(true);
            }            
        });
    });
    

    Example

    You can try the code of course

    Maybe it’s not the optimal solution, since it starts searching for the start node from the root. It would be faster to search from the first common parent element of range.startContainer and range.endContainer, but I don’t know how to do that…

    Edit

    I wrapped the to-X functions inside if(range.collapsed == false) and used range.commonAncestorContainer.childNodes[0] in order to start iterating through the elements from the first child of the common parent of the start and end position of the selection

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 366k
  • Answers 366k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer In the particular case of $.ajax(), this can be specified… May 14, 2026 at 4:43 pm
  • Editorial Team
    Editorial Team added an answer The error indicates, that you are trying to run a… May 14, 2026 at 4:43 pm
  • Editorial Team
    Editorial Team added an answer Found a solution; we use the YUI compressor to compress… May 14, 2026 at 4:43 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.