2016-06-23 66 views
1

我有這樣的句子:如何在每次出現時用隨機值替換正則表達式?

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

你能幫我得到的東西通過一個隨機值,而不是全局替換替換每個模式?

我不知道如何循環正則表達式的結果來替換原始語句中的匹配(每次都有隨機值)。

+1

使用回調函數進行替換,並讓它返回隨機值。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter – CBroe

+0

@CBroe的確......我用一個返回隨機值的函數替換了'randomValue',它作品! – Alex

回答

2

replace接受一個函數作爲它的第二個參數,爲每個替換函數調用它,並且可以返回要替換的值。所以,使用功能和移動隨機數生成到它:

String.prototype.replacePatterns = function (hash) { 

    var string = this, 
     key, 
     entry; 

    for (key in hash) { 
     if (hash.hasOwnProperty(key)) { 
      entry = hash[key] 
      string = string.replace(new RegExp('\\<' + key + '\\>', 'gm'), function() { 
       return entry[Math.floor(Math.random() * entry.length)] 
      }); 
     } 
    } 

    return string; 
}; 

你不需要在這裏,但僅供參考,函數接收匹配的文本作爲第一個參數,如果你在捕捉組你的正則表達式(你沒有),它接收它們作爲後續的參數。詳情請見the MDN page for String#replace或當然the spec

1

您也可以使用正則表達式來代替循環。類似於

function replacePatterns(str, options) { 
    options = options || { 
    adjective: ['big', 'small', 'funny'], 
    noun: ['dog', 'horse', 'ship'], 
    title: ['bar', 'pub', 'club'] 
    } 

    return str.replace(/<(.*?)>/g, function(match) { 
    match = match.replace(/<|>/g,'') 
    return options[match][Math.floor(Math.random()*options[match].length)] 
    }) 
} 

還添加了可選的options哈希值以增加靈活性。