user2261185
user2261185

Reputation: 11

How to make a .replace loop in javascript?

I am currently trying to make a .replace function loop in javascript. What I am trying to do is replace a random character with a hyphen, but the part that I am struggling with is how to make it loop the replacing of the character to hyphen. Here is the code that I have so far:

    var randHold;
    var randomWord;
    var randLetHold;
    var dispWord;
    var repLetHold;

    var myWords = new Array("Spectrometer", "Bandwagonjghvyjh", "jvjyvyvilvyjlvyv", 
                            "fruitjjyvtyvjv", "seventctcvtv", "weathertfhtcthc", 
                            "undercfxdtfv"); // random letters to make words that have more than 10 letters

    function level() { 
        randHold = parseInt((Math.random() * 6) + 1);//code to randomly pick a word from the above array
        randomWord = myWords[randHold]; //code to call the random word from the array
        randLetHold = (Math.random() * randomWord.length);//code to randomly pick a character from the random word chosen
        repLetHold = randomWord.charAt(randLetHold);//code to call the random character
        for (i = 1; i <= 3; i++) //loop to replace three random characters with a hyphen 
        {
            dispWord = randomWord.replace(repLetHold," - ");//code to replace a random character with a hyphen
            document.write(dispWord);//But all this does is display the word(with ONE hypenated character)three times.
        }

    }

Upvotes: 1

Views: 2523

Answers (4)

Xotic750
Xotic750

Reputation: 23502

For 3 random characters to be hyphenated in the word, you want something like this.

<div id="result"></div>

var myWords = ["Spectrometer", "Bandwagonjghvyjh", "jvjyvyvilvyjlvyv",
    "fruitjjyvtyvjv", "seventctcvtv", "weathertfhtcthc",
    "undercfxdtfv"]; // random letters to make words that have more than 10 letters

var randomWord;
var dispWord;
var repLetHold = [];

function uniqueCount(str) {
    var unique = [];

    Array.prototype.forEach.call(str, function (value) {
        if (unique.indexOf(value) === -1) {
            unique.push(value);
        }
    });

    return unique.length;
}

function level() {
    var randHold = Math.floor(Math.random() * myWords.length);

    dispWord = randomWord = myWords[randHold];
    if (uniqueCount(randomWord) > 2) {
        var count = 0,
            temp1,
            temp2;

        while (count < 3) {
            temp1 = Math.floor(Math.random() * dispWord.length);

            temp2 = dispWord.charAt(temp1);
            if (temp2 !== "-" && repLetHold.indexOf(temp2) === -1) {
                dispWord = dispWord.replace(new RegExp(temp2, "g"), "-");
                repLetHold[count] = temp2;
                count += 1;
            }
        }
    }

    document.getElementById("result").textContent = dispWord;
}

level();

console.log(randomWord, repLetHold);

on jsfiddle

Upvotes: 1

bmceldowney
bmceldowney

Reputation: 2305

Your code actually seems fine, the main issue is that you're declaring your random variables outside of your for loop. Doing this will only generate them once for the entire loop. Try this instead:

var dispWord;

var myWords = new Array("Spectrometer", "Bandwagonjghvyjh", "jvjyvyvilvyjlvyv", 
                        "fruitjjyvtyvjv", "seventctcvtv", "weathertfhtcthc", 
                        "undercfxdtfv"); // random letters to make words that have more than 10 letters

function level() { 
    for (i = 1; i <= 3; i++) //loop to replace three random characters with a hyphen 
    {
        var randHold = parseInt((Math.random() * 6) + 1);//code to randomly pick a word from the above array
        var randomWord = myWords[randHold]; //code to call the random word from the array
        var randLetHold = (Math.random() * randomWord.length);//code to randomly pick a character from the random word chosen
        var repLetHold = randomWord.charAt(randLetHold);//code to call the random character

        dispWord = randomWord.replace(repLetHold," - ");//code to replace a random character with a hyphen
        document.write(dispWord);//But all this does is display the word(with ONE hypenated character)three times.
    }

}

Upvotes: 1

user2264587
user2264587

Reputation: 474

http://jsfiddle.net/zt8mp/

If i got the question right:

randomWord.replace(new RegExp(repLetHold,'g')," - ")

replaces all occurences of repLetHold (as long as it is not made of special regex characters)

Upvotes: 0

bfavaretto
bfavaretto

Reputation: 71939

If you use a regular expression, you can replace all instances at once with the g (global) flag. For example:

var str = "this is a mass Spectrometer, which is a Spectrometer to detect the spectra of different masses";
var replaced = str.replace(/Spectometer/g, 'something');
// "this is a mass something, which is a something to detect the spectra of different masses";

Just keep in mind that some characters must be escaped inside regular expressions.

Upvotes: 0

Related Questions