I'm trying to make a 'find and replace' function that takes both values (replaced and replacement) from Form element and then replaces all occurances of 'replaced' inside DIV. After that I want it to display an alert with a replaced words count.
Tried to get there with the for loop, but something went wrong. Going with plain JS, I'm way too novice to get into jQuery.
function wordReplace()
{
var replaced = document.getElementById('replaced').value.toLowerCase;
var replacement = document.getElementById('replacement').value;
var workArea = document.getElementById('main').innerHTML;
for (var r=0; r<workArea.lenght; r++)
{
if (workArea[r].value.toLowerCase == 'replaced')
{
workArea[r].value.replace('\breplaced', 'replacement')
alert(workArea[r].value.replace('replaced', 'replacement').length)
}
}
}
And that's my form code, just in case: (ignore <input type="submit" onclick="replacerHide();"/> - it's for different function and it works for now)
<form>
<label for="replaced" class="labelInline">Słowo szukane</label>
<input type="text" name="replaced" id="replaced"/>
<label for="replacement" class="labelInline">Zamiennik</label>
<input type="text" name="replacement" id="replacement"/>
<input type="submit" onclick="replacerHide();"/>
</form>
I've read here (in a similliar question of mine) that I should get familliar with regex and I did. But have no faintest idea how to apply it to solve my problem. I'm pretty sure I'm onto something with for loop here, but other than that I'm empty :/
All and any help will be GREATLY appreciated.
EDIT - CORRECTED FULLY WORKING CODE
function wordReplace()
{
var div = document.getElementById('main');
var find = document.getElementById('replaced').value;
var replace = document.getElementById('replacement').value;
var re_Find = new RegExp(find, 'gi');
var matches = div.innerHTML.match(new RegExp(find, 'gi'));
if (matches)
{
div.innerHTML = div.innerHTML.replace(re_Find, replace);
}
matches = matches ? matches.length : 0;
alert(matches);
}
and for the Form
<div id="form">
<form id="formularz">
<label for="replaced" class="labelInline">Słowo szukane</label>
<input type="text" name="replaced" id="replaced"/>
<label for="replacement" class="labelInline">Zamiennik</label>
<input type="text" name="replacement" id="replacement"/>
<button onclick="replacerHide(); wordReplace();">Podmień!</button>
</form>
Now it's working as it is supposed to :)
.replace()(as in your inner loop) doesn't change the string you called it on. You need to use the string returned from.replace().