简体   繁体   中英

Replacing all of the repeated characters in javascript

function duplicateEncode(word){
  var i;
  var j;
  for(i = 0; i < word.length; i++) {
    for(j = i + 1; j < word.length; j++) {
      if (word[i] == word[j]) {
        word = word.replace(/word[i]/gi, ')');
      }
      else word = word.replace(/word[i]/gi, '(');
    };
  };
  return word;
}

I need to get ( if character is not repeated in the word and this ) if it is and this code doesnt work it just gives me the word back that I type in.

You are not using regex properly. Here is one possible solution based off of your original code. As you know, Strings are immutable in Javascript so we need to rebuild the string every time using your approach.

 function duplicateEncode(word){ for(i = 0; i < word.length; i++) { if (word[i] == word[i+1]) { word = word.substring(0,i) + ')' + word.substring(i+1); } else { word = word.substring(0,i) + '(' + word.substring(i+1); } } return word; }

To avoid rebuilding the string we can store the characters in an array and then join them at the end for a performance boost for large strings.

 function duplicateEncode(word){ const newWordArr = []; for(i = 0; i < word.length; i++) { if (word[i] == word[i+1]) { newWordArr.push(')'); } else { newWordArr.push('('); } } return newWordArr.join(''); }

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