我的代码自动在字符串中搜索颜色名称,并添加随机数后缀并将其作为元素存储在数组中。

我想要的是使用数组的新修改元素创建一个新字符串。

当字符串多次出现相同颜色名称时,就会出现问题。

我需要的是用导出的数组的不同元素一一替换这些情况。

(我不想在Array中拆分字符串,将相同的元素替换为全新的另一个数组,然后将其连接到字符串。我需要修改原始字符串)

例:

字符串通过用户输入改变,所以如果我有:

 str = ' little red fox is blue and red cat is blue';


然后我的代码找到所有颜色名称并生成一个新数组,如下所示:

array = [ 'red2354' , 'blue7856' , 'red324', 'blue23467'] ;


(我的代码在每个颜色元素的末尾添加了RANDOM后缀,但我的数组的顺序与字符串的出现相同)

所需输出:

 str = ' little red2354 fox is blue7856 and red324 cat is blue23467 ';


到目前为止,我尝试过:

var str = ' little red fox is blue and red cat is blue ';

//I have split string to Array:

ar1 = [ "little","red","fox","is","blue","and","red","cat","is","blue"];

//var dup = matchmine(ar1) find all color duplicates :

var dup = ["red","blue","red","blue"];

//I've sorted all duplicates to appear only once for option B:

var dup2 = ["red","blue"];

//var res = modify(str) takes all color names and adds random suffixes:


var res= ["redA" , "blueA" , "redB", "blueB" ] ;

//I have also create a new array with all strings in case I needed to match lengths:

var final = [ "little","redA","fox","is","blueA","and","redB","cat","is","blueB"];




   var i = ar1.length-1;

       for ( i ; i >= 0; i--) {

    var finalAr = str.replace(ar1[i],final[i]);
    str = finalAr;}

    alert(finalAr);


问题是循环进行,第一次将所有元素一一替换。到目前为止一切顺利,但在以下循环中再次替换了第一个循环。

循环结果:

   str = 'little redAB fox is blueAB and red cat is blue '


所需的输出:

 str = 'little redA fox is blueA and redB cat is blueB '

最佳答案

您的某些逻辑仍然隐藏在您的问题中,例如您基于什么理由确定哪个单词应带有后缀,或者如何确定该后缀。

所以我的回答不能完整。我将假定所有重复的单词(包括“是”)。如果您已经知道如何隔离应该考虑的单词,则可以将您的单词选择逻辑插入我寻找重复项的位置。

为了确定后缀,我提供了一个非常简单的函数,该函数在每次调用时(依次)产生一个唯一的数字。同样,如果您有更合适的逻辑来生成这些后缀,则可以在此处注入代码。

我建议您使用已识别的单词创建一个正则表达式,然后使用该正则表达式在字符串上调用replace并使用callback参数添加动态后缀。

码:



function markDupes(str, getUniqueNum) {
    // 1. Get all words that are duplicate (replace with your own logic)
    let dupes = str.match(/\S+/g).reduce(({words, dupes}, word) => ({
        dupes: words.has(word) ? dupes.concat(word) : dupes,
        words: words.add(word)
    }), {words: new Set, dupes: []} ).dupes;
    // Turn those words into a regular expression. Escape special characters:
    dupes = dupes.map(word => word.replace(/[\/\\^$*+?.()|[\]{}]/g, '\\$&'))
                 .join("|");
    let regex = new RegExp(dupes, "g");
    // Make the replacement of duplicate words and call the callback function:
    return str.replace(regex, word => word + getUniqueNum());
}

// Example has two inputs:

// 1. A function that determines the suffix:
//   Every call should return a different value
var getUniqueNum = ((i = 1) => {
    // ... here we choose to just return an incremental number
    //  You may implement some other (random?) logic here
    return () => i++;
})();

// 2. The input string
let str = 'little red fox is blue and red cat is blue ';

// The call:
console.log(markDupes(str, getUniqueNum));

09-20 21:12