On first glance, other answers don't handle page load (maybe they do and I'm missing something...). Both localStorage or cookies are fine, it doesn't make much difference which you pick for this problem. You should try both, just for practice.
I added a delete cookies button, for your convenience (Edit: it doesn't delete the cookie, just sets it to empty string)
<script>
// either we can read a cookie
// or the cookie is empty -> then we pick a random name and set is as cookie
window.onload = function() {
var randomname = getCookie('randomname');
if(randomname != '') {
setName(randomname);
}
else {
setCookie('randomname', replaceName());
}
}
function replaceName() {
var textArray = ['Mark', 'Jane', 'Aldrin', 'Len'];
var randomIndex = Math.floor(Math.random() * textArray.length);
var randomElement = textArray[randomIndex];
setName(randomElement);
return randomElement; // we would like to know the name, just the name, so we can store it somewhere
}
// I take this code out of replaceName() and set it in a separate function.
// so you can use it both for setting the name from cookie as for the random name
function setName(name) {
var text1 = "Hi, I'm ";
var text2 = ", How can i help you?";
var text3 = text1.concat(name, text2);
document.getElementById("demo").innerHTML = text3;
}
function deleteCookies() {
setCookie('randomname', '');
}
// Get and Set cookie; @see https://www.w3schools.com/js/js_cookies.asp
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
</script>
<div id="demo"></div>
<input type="button" value="delete cookie" onclick="deleteCookies()"/>
What I would advise: try using better names for functions; make sure the name of the function discribes what you intend to do.
You notice I cut your function in half, I made two functions out of it. Since setName is needed both for a new name and for a name that was saved in a cookie or localstorage, it's better to have it as a separate function