I have a challenging mission in JS string manipulation: There is a HTML string in which I need to replace a word at a specific word index. The word index is the number of the word when ignoring the HTML tags.
For example, here is the HTML string:
<span style="font-family:Times New Roman;">At times like this I don't know what to
do. Other times I have no problem.</span>
The task is to replace word number 2 in the html (which is the word times) with the text: <span style="color:red;">times</span>
So the final HTML string should be:
<span style="font-family:Times New Roman;">At <span style="color:red;">times</span>
like this I don't know what to do. Other times I have no problem.</span>
Any ideas for this challenge?
I think a decent solution would be to split and replace then join. Here's an example:
Should result in:
And here's a JSFiddle for you to see it in action
ive been using this jQuery plugin to replace/edit text in any part of the DOM. quite helpful and easy to use with complete REGEX support
http://benalman.com/projects/jquery-replacetext-plugin/
I would first find the word by tokenizing the filtered HTML, and then do the replacement.
Let's start from your string :
Case 1, you want to replace all occurrences :
Demonstration
Case 2, you just want to replace the word at the specified index (this one is surprisingly tricky) :
Demonstration
Alternate solution for case 2 :
Can you spot why the second one was tricky ? ;)
> call the smartReplace() like follows