0

I have a div which has the contenteditable property set to true. I want to be able to get the range of a string in the div. The range should contain the starting offset(relative to the text content of the div) of that particular word and if possible the length of the word.

For example, if the string in the div contains "This is a test" , I want to be able to get the range of the string "test" dynamically ( I would not know how many characters are there). For now, the div would only contain text.

It would be great if someone could help me out with this.

learner2010
  • 4,157
  • 5
  • 43
  • 68
  • More detail required. What should this "range" consist of? Can the
    contain other HTML elements or just text?
    – Tim Down Oct 15 '12 at 14:24
  • The range should contain the starting offset of that particular word. The div for now would contain only text. Also added the same details to my question. – learner2010 Oct 15 '12 at 14:32
  • thank you.. but that solution is for getting the range of the user selected text in the div right? I want to search for a particular string in the text of the div and get its starting offset. – learner2010 Oct 15 '12 at 14:41
  • no problem.. but thats a useful link as well.. will be useful for me later on.. thanks.. – learner2010 Oct 15 '12 at 14:57

1 Answers1

1
"This is a test".indexOf("test")

or more generic

String.indexOf(testString)

will give you the offset of testString in String starting at index 0, with -1 returned if testString is not contained in String. Your example would return 10.

Christoph
  • 50,121
  • 21
  • 99
  • 128
  • working based on this.. say I type in the same word twice, how would I find the starting offset of the 2nd word? – learner2010 Oct 15 '12 at 18:46
  • You can hand over an additional parameter which is the position where to start in the string. Use it in a while loop to get all occurrences. – Christoph Oct 15 '12 at 19:48