【问题标题】:How to replace from regex with random value at each occurrence?如何在每次出现时用随机值替换正则表达式?
【发布时间】:2016-06-23 12:08:35
【问题描述】:

我有这样的句子:

var str = 'The <adjective> <noun> and <noun> <title>';

我想用相关数组中的随机值替换每个 &lt;pattern&gt;

在我之前的示例中,我希望得到类似于:

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

在同一个句子中两次使用相同的模式(例如&lt;noun&gt;),我几乎明白了。所以我只为每个模式生成一个随机值...

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

你能帮我用随机值而不是全局替换来替换每个模式吗?

我不知道如何循环正则表达式的结果来替换原句中的匹配项(每次都是随机值)。

【问题讨论】:

标签: javascript regex random replace


【解决方案1】:

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#replacethe spec 中的详细信息。

【讨论】:

    【解决方案2】:

    您也可以使用正则表达式来代替循环。类似的东西

    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 哈希中添加以增加灵活性。

    【讨论】:

      猜你喜欢
      • 2017-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      相关资源
      最近更新 更多