vendredi 29 mai 2015

How to improve find and replace function in javascript

I've got this neat find and replace from form input function, with which You people helped me a lot. Now, I would want to improve it a bit. For time being script is taking all kind of data put into my forms - words, single characters, commas, spaces and such. I want it to take in only full words, preferably even few at a time (but not neccessarily sentences, if that makes any sense to You) and discard unwanted rest with return message of `search params invalid'. Thing is I'm just starting with JavaScript (I'm scared stiff of jQuery) and apparently got a little in over my head with it. But geting on, that's my 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);
            }
        else if (document.getElementById('replaced').value == "")
            {

            }
            matches = matches ? matches.length : 0;
            alert("Zamieniono " + matches + " słów!");

As You can see, it takes everything and anything in now. Figured else if is a way to go, but I hit the wall since then. Any ideas what to do next?

Aucun commentaire:

Enregistrer un commentaire