0

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 :)

3
  • What does the console output says ? I see workArea.lenght , as I know it should have been 'length' so your code should produce an error Commented May 28, 2015 at 14:22
  • Note that just calling .replace() (as in your inner loop) doesn't change the string you called it on. You need to use the string returned from .replace(). Commented May 28, 2015 at 14:24
  • Corrected the typo, but even with it still in code console gave me no errors. Commented May 28, 2015 at 14:53

2 Answers 2

1

Try some regexp.

function replace(find, replace, haystack) { 
    return haystack.replace(new RegExp(find,"gmi"),replace);
    }
function count(find, haystack) { 
        return haystack.match(new RegExp(find,"gmi")).length;
    }
window.alert(replace ("hello","bye","hello world? Hello person! and hello universe!"));
window.alert("Number of matches: "+count("hello","hello world? Hello person! and hello  universe!"));

Sign up to request clarification or add additional context in comments.

3 Comments

all of them. it matches all strings over all lines case insentive. If you run the snippet you see that it has replaced all 3 hello's. To have it case sensitive, remove the i in the Regexp object.
From the OP: "After that I want it to display an alert with a replaced words count."
Ah, missed that. added a counting function.
0

Regular expressions are your friend with things like this, as well as replace

By specifying the options gi to the RegExp constructor you can eliminate the need to check for character case (i means case-insensitive). The g means "global" and tells the regular expression you want to repeat the replacement for every instance of find that was found (by default, it will replace the first and then stop).

// Grab all of the necessary data
var div = document.getElementById('main');
var find = document.getElementById('replaced').value;
var replace = document.getElementById('replacement').value;

// Create our regular expression
var re_Find = new RegExp(find, 'gi');

// Get everything from the div's innerHTML that matches our regular expression
// (this will result in an array of strings, all of which are exactly
// the same as "find")
var matches = div.innerHTML.match(re_Find);

// If there were any matches, use the same regular expression to
// perform the actual replace and update the div
if (matches) {
  div.innerHTML = div.innerHTML.replace(re_Find, replace);
}

// Grab the count of matches that were found and alert the user
matches = matches ? matches.length : 0;
alert(matches);

7 Comments

Did as You suggested and sadly - no avail. Even no errors. I'm starting to think that problem might be somewhere else, but where? :/
Try putting console.log(find, replace, div.innerHTML) after the first 3 var declarations, and have a look in the console to see what values they contain.
Console returns nothing. And I mean it's completely empty. Other functions are working fine.
I made a jsbin for you to play with..
I fixed it without jQuery. Thing is I retyped your hint mindlessly and made a typo in var find = document.getElementById('replaced').value; (replace instead of correct replaced). But it's all working now. I'll update the question with correct code in a sec.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.