0

Is there some way to replace a specific string within a HTML element with another string? I tried using .replace() but there was no effect (and no error message in the console either). See code below.

month = 1
date = document.getElementById('date');
date.innerHTML = month + ' months';

if (month == 1) {
    date.innerHTML.replace('months', 'month');
}

3 Answers 3

2

The replace method actually doesn't change the content of the string, it generates a new string with the desired changes, so you should assign it to some variable, or use it as some function parameter.

So in your case, you're just missing reassign it to the date.innerHTML like:

date.innerHTML = date.innerHTML.replace('months', 'month')
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Rookie mistake. I marked your answer since you provided an explanation.
We all commit those, no worries, thanks for marking me.
2

It should be

month = 1
date = document.getElementById('date');
date.innerHTML = month + ' months';

if (month == 1) {
    date.innerHTML = date.innerHTML.replace('months', 'month');
}

Comments

1

Replace to

date.innerHTML =  date.innerHTML.replace('months', 'month');

Comments

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.