簡體   English   中英

如何在JavaScript中制作.replace循環?

[英]How to make a .replace loop in javascript?

我目前正在嘗試在JavaScript中創建一個.replace函數循環。 我想做的是用連字符替換隨機字符,但是我苦苦掙扎的部分是如何使它循環將字符替換為連字符。 這是我到目前為止的代碼:

    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.
        }

    }

對於單詞中要連字符的3個隨機字符,您需要這樣的內容。

<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);

jsfiddle上

您的代碼實際上看起來不錯,主要的問題是您在for循環之外聲明了隨機變量。 這樣做只會為整個循環生成一次。 嘗試以下方法:

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.
    }

}

如果使用正則表達式,則可以一次用g (全局)標志替換所有實例。 例如:

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";

請記住, 某些字符必須在正則表達式內轉義

http://jsfiddle.net/zt8mp/

如果我的問題正確:

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

替換所有出現的repLetHold (只要它不是由特殊的正則表達式字符組成)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM