我有這樣的句子:如何在每次出現時用隨機值替換正則表達式?
var str = 'The <adjective> <noun> and <noun> <title>';
我想從他們的相關陣列的隨機值來代替每個<pattern>
。
在我以前的例子,我想獲得類似於:
var adjectives = ['big' 'small' 'funny'];
var nouns = ['dog', 'horse', 'ship'];
var title = ['bar', 'pub', 'club'];
var str = 'The <adjective> <noun> and <noun> <title>';
var r = str.replacePatterns({ noun: nouns, adjective: adjectives, title: titles });
console.log(r); // The big horse and ship club
我通過沒有強硬大約相同的模式幾乎得到它(例如<noun>
。)兩次在同一個句子。所以我只產生一個對每個圖案隨機值...
String.prototype.replacePatterns = function (hash) {
var string = this,
key;
for (key in hash) {
if (hash.hasOwnProperty(key)) {
var randomValue = hash[key][Math.floor(Math.random() * hash[key].length)];
string = string.replace(new RegExp('\\<' + key + '\\>', 'gm'), randomValue);
}
}
return string;
};
你能幫我得到的東西通過一個隨機值,而不是全局替換替換每個模式?
我不知道如何循環正則表達式的結果來替換原始語句中的匹配(每次都有隨機值)。
使用回調函數進行替換,並讓它返回隨機值。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter – CBroe
@CBroe的確......我用一個返回隨機值的函數替換了'randomValue',它作品! – Alex