1

I have a ContentEditable Section. I want to get what the user selects, and then replace it with a new string.

So I will want the start and end of selected string, remove the old string, put the new string in place (will be longer).

Example:

Typed String: 'Hello, World!'
Selected String: 'World'
String to replace with: '** World **'

I want to add 'stars' around that selected word, like StackOverflow does for making text bold.

I have read countless questions on StackOverflow, but none could answer this question. And I have tried so many snippets which don't work. :P.

Note: I'm using jQuery.

Thanks.

Arjun Bajaj
  • 1,932
  • 7
  • 24
  • 41
  • I'm having the same problem. The often repeated code-fragment to "replace the current selection" doesn't work in chrome content-editable.. For some reason, window.getSelection is returning a selection outside the contentEditable region (as if there are two selection contexts) – David Jeske Aug 15 '12 at 15:58

2 Answers2

1

This thread is based on wrapping selected text in a span... very close to what you want. The code and fiddles should give you what you need

Wrapping a selected text node with span

Community
  • 1
  • 1
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0
var str = 'Hello, World!'; var foo = 'World'; var bar = '** World **';

str = str.replace(foo, bar);
SenorAmor
  • 3,351
  • 16
  • 27
  • this will work as long as the replace word is the first in the text. Suppose its later, I want to use the position of the start of the string to replace. Not the replace() function which only replaces the word with another word. – Arjun Bajaj Feb 28 '12 at 03:17