Macchiato
Macchiato

Reputation: 260

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?

Upvotes: 1

Views: 4685

Answers (2)

Julian H. Lam
Julian H. Lam

Reputation: 26124

.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'));

Upvotes: 7

njr101
njr101

Reputation: 9619

You need to apply the new string value to the DOM element

document.getElementById("replace-them").innerHTML =
    document.getElementById("replace-them").innerHTML.replace("New York", "New York City");
// etc.

Incidentally, after defining the function replaceWords() you also need to make sure you actually call it.

You also need to use a div or similar element for the markup to render correctly.

Working fiddle here.

Upvotes: 3

Related Questions