0

I am trying to replace selected text with another text.
Consider following is the line of text.

Hello world.Good morning. Hello world. Good morning.

Here if I select second morning text and I want replace morning text with night. So that output need to look like this:

Hello world.Good morning. Hello world. Good night.

I tried replace function, but it is replacing first morning text.
Can anyone suggest solution for this?

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Sujit
  • 610
  • 7
  • 26
  • 2
    Where is this text located? In a `textarea`/`input` or part of the text of a DOM element? – Rory McCrossan Jan 07 '13 at 12:52
  • Are you having problems with the selected text or with the replacing? You can replace all occurrences using `str.replace(/\\n/g, '
    ');` (taken from http://stackoverflow.com/questions/6064956/replace-all-occurrences-in-a-string )
    – Pablo Jan 07 '13 at 12:53
  • similar problem http://stackoverflow.com/questions/36183/replacing-the-nth-instance-of-a-regex-match-in-javascript – Cris Jan 07 '13 at 13:02

2 Answers2

3

To get the current selection in HTML5, use the DOM Range API.

To edit the selection, the Selections API can be used.

See also: Where did the Text Selection API go?

If you use jQuery, then use the wrapSelection plugin

Community
  • 1
  • 1
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
1

You could do it like this:

SEE DEMO

function swapSelection(swapText) {
  var sel = window.getSelection ? window.getSelection() : document.selection.createRange();
  if (sel != "") {
    if (sel.getRangeAt) {
      var range = sel.getRangeAt(0);
      var newNode = document.createElement("span");
      newNode.setAttribute('class', 'swapclass');
      range.surroundContents(newNode);
    } else {
      sel.pasteHTML('<span class="swapclass">' + sel.htmlText + '</span>');

    }
    $('.swapclass').replaceWith(swapText);
  }
}

$('button').click(function () {
  swapSelection('night');
});
A. Wolff
  • 74,033
  • 9
  • 94
  • 155