This is your solution with the least modification.
The problem with your code is using String.prototype.charAt to find and replace your character, and it finds the first occurrence of a character. So when a character is repeated in your string, charAt will find and replace the first occurrence, not the other ones.
So you can define a function like replaceAt below, to replace a character at a specific position, and use that.
let title1 = "Your sales place";
let title2 = "Software Hub";
String.prototype.replaceAt = function(index, replacement) {
return this.substr(0, index) + replacement + this.substr(index + replacement.length);
}
var k = 0;
var speed = 150;
function typeWriter() {
if (k < title1.length) {
if (k >= title2.length) {
title2 += title1[k];
} else {
title2 = title2.replaceAt(k, title1[k]);
}
document.getElementById("demo").innerHTML = title2;
k += 1;
setTimeout(typeWriter, speed);
}
}
typeWriter();
<div id="demo"></div>
However, I would recommend that you do not use global variables as counters when recursively calling a function, instead, pass that variable to your function:
let title1 = "Your sales place";
let title2 = "Software Hub";
var speed = 150;
String.prototype.replaceAt = function(index, replacement) {
return this.substr(0, index) + replacement + this.substr(index + replacement.length);
}
function typeWriter(k) {
if (k < title1.length) {
let title = document.getElementById("demo").innerHTML
if (k >= title.length) {
title += title1[k];
} else {
title = title.replaceAt(k, title1[k]);
}
document.getElementById("demo").innerHTML = title;
setTimeout(() => {typeWriter(k+1)}, speed);
}
}
document.getElementById("demo").innerHTML = title2;
setTimeout(() => {typeWriter(0);}, speed)
<div id="demo"></div>