简体   繁体   中英

Replace words in var string by elements of array in JS

My code automatically search the string for color names and adds random number suffixes and stores them as elements in an array.

What I want is to create a new string with the new modified elements of my array.

Problem comes when string has multiple occurrences of the same color name.

What I need is to replace these occurrences with the different elements of my exported array one by one.

(I don't want to split string in Array, replace the same elements with the other array in a brand new one and then join it to a string. I need to modify the original string)

Example:

String changes through user input so if i have:

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

then my code finds all color names and produces a new array like that:

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

(my code adds RANDOM suffixes at the end of every color element but the order of my array is the same as the string's occurrences)

Desired Output:

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

I tried so far:

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

Problem is that loop goes and 1st time replace one by one all elements. So far so good but in the following loops replace the first again.

loops result:

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

Desired output:

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

Make an object that works as a map for your replacers:

const replacers =   {
    red: 'redA', 
    blue: 'blueB' 
}

Then split your string into an array of words and map over it, replacing as you go:

const inputStr = 'this is my red string blue words' 
const stringArr = inputStr.split(' ') 
const result = stringArr.map(word=> replacers[word]?replacers[word]:word). join(' ') 

Some of your logic remains hidden in your question, like on what grounds you determine which word should get a suffix, or how that suffix is determined.

So my answer cannot be complete. I will assume all words that are duplicate (including "is"). If you already know how to isolate the words that should be taken into consideration, you can just inject your word-selection-logic where I have looked for duplicates.

For the suffix determination, I provide a very simple function which produces a unique number at each call (sequentially). Again, if you have a more appropriate logic to produce those suffixes, you can inject your code there.

I suggest that you create a regular expression from the words that you have identified, and then call replace on the string with that regular expression and use the callback argument to add the dynamic suffix.

Code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM