vietnguyen vietnguyen -3 years ago 199
Javascript Question

javascript convert space to symbol in string

How to convert the space between letters into another character like "-"? Here's my code:

// list of names
var names = ["John Smith", "Joe Doe", "Ian Nobody", "James Black"];
var namePicked = names[Math.floor(Math.random() * names.length)];
var nameArray = new Array(namePicked.length);

window.onload = function() {
//convert chosen name to array and replace letters with dashes
for (var i = 0; i < nameArray.length; i++) {
nameArray[i] = "_";
}
//remove comma
var nameHidden = nameArray.join(" ");
document.getElementById("nameDisplay").innerHTML = nameHidden;
}


I can only turn John Smith into a line of 10 underscores, I want to make it 4
underscores
(first name) with a
dash
(for the space) before the last 5
underscores
(last name). Also a
space
between each
underscore
. I'm sorry I didn't mention this earlier.
I've tried this:

for (var i = 0; i < nameArray.length; i++) {
if (nameArray[i] == " ") {
nameArray[i] = " ";
}
else {
nameArray[i] = "_";
}
}


And some other variations but none works.

Answer Source

Try this

<script>
    var names = ["John Smith", "Joe Doe", "Ian Nobody", "James Black"];
    var namePicked = names[Math.floor(Math.random() * names.length)];


    window.onload = function () {
        var nameoutput = "";
        for (var i = 0; i < namePicked.length; i++) {
            if (namePicked[i] == " ") {
                nameoutput += " ";
            }
            else {
                nameoutput += "X";
            }
        }
        document.getElementById("nameDisplay").innerHTML = nameoutput;
    }
</script>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download