Search code examples
javascriptreplaceinnerhtmlgetelementbyidwords

Find certain words and replace them


I'd like to find:

"New York" and replace it with "New York City"
"Washington" and replace it with "Seattle"
"Florida" and replace it with "Jacksonville"
"South-Carolina" and replace it with "Columbia"
"West_Virginia" and replace it with "Charleston"

I made the following example code below, but that doesn't seem to work:

Demo: http://jsfiddle.net/N3ZmS/

<td id="dont-replace-them">
New York<br />
Washington<br />
Florida<br />
South-Carolina<br />
West_Virginia<br />
</td>

<br />

<td id="replace-them">
New York<br />
Washington<br />
Florida<br />
South-Carolina<br />
West_Virginia<br />
</td>

<script type="text/javascript">
function replaceWords() {
    document.getElementById("replace-them").innerHTML.replace("New York", "New York City");
    document.getElementById("replace-them").innerHTML.replace("Washington", "Seattle");
    document.getElementById("replace-them").innerHTML.replace("Florida", "Jacksonville");
    document.getElementById("replace-them").innerHTML.replace("South-Carolina", "Columbia");
    document.getElementById("replace-them").innerHTML.replace("West_Virginia", "Charleston");
};  
</script>


Anyone know what should be fixed to make it work?


Solution

  • .replace(); returns the replaced string, it doesn't alter the string in the DOM.

    var str = 'foobar';
    str.replace('foobar', 'lorem ipsum');    // Returns 'lorem ipsum', but does no DOM manipulation.
    

    You'll need to save the results of each .replace() into a temporary variable, and then update the DOM afterwards.

    function replaceWords(el) {
        el.innerHTML = el.innerHTML
                        .replace('New York', 'New York City')
                        .replace('Washington', 'Seattle')
                        .replace('Florida', 'Jacksonville')
                        .replace('South-Carolina', 'Columbia')
                        .replace('West_Virginia', 'Charleston');
    }
    
    replaceWords(document.getElementById('replace-them'));