Home > OS >  Specific Array element replace
Specific Array element replace

Time:10-14

I'm solving a simple problem where I need to capitalize the first alphabet of all words. I was able to do that but I have another string vn52tqsd0e4a if any of my output is matched with this string I have to replace it with --[matched string]-- . so the expected output should be H--e--llo Worl--d-- but when I'm trying to replace the element with -- it's not doing anything. I tried replace() method as well but it didn't work. I don't know what I'm doing wrong here.

function LetterCapitalize(str) {
 // code goes here
 let array = str.split(" ")
 for (let i=0; i<array.length; i  ){
     array[i] = array[i].charAt(0).toUpperCase()   array[i].slice(1)
 } 
let output = array.join(" ") ;
let comp = "vn52tqsd0e4a".split("");
  for (let i=0; i<output.length; i  ){
    comp.map(el=> {
      if(output[i] === el){
        console.log( `matched ${output[i]}` )
        output[i] = `--${output[i]}--`;
        console.log(output[i]);
      }
    })
//   
  }
   console.log(output);

} 


LetterCapitalize("hello world");

CodePudding user response:

You can achieve this using split, map, join as:

function LetterCapitalize(str) {
  // code goes here
  let array = str.split(' ');
  for (let i = 0; i < array.length; i  ) {
    array[i] = array[i].charAt(0).toUpperCase()   array[i].slice(1);
  }
  let output = array.join(' ');
  let comp = 'vn52tqsd0e4a'.split('');
  const result = output
    .split('')
    .map((c) => (comp.includes(c) ? `--${c}--` : c))
    .join('');
  console.log(result);
}

LetterCapitalize('hello world');

CodePudding user response:

You coulduse Array.reduce() to iterate over the str argument and either capitalize or replace depending on the character.

If the preceeding value is a space we'll capitalize, otherwise if the character is in the comp value, we'll replace with --${char}--.

function LetterCapitalize(str) {
    const comp = "vn52tqsd0e4a";
    return [...str].reduce((acc, char, idx, a) => { 
        if (idx === 0 || a[idx - 1] === ' ') {
            char = char.toUpperCase();
        } else if (comp.includes(char)) { 
            char = `--${char}--`;
        }
        return acc   char;
    }, '')
}

console.log(LetterCapitalize("hello world"));
console.log(LetterCapitalize("hey man"));

CodePudding user response:

What you say to JavaScript in the piece of code is that it should fit 5 characters in a place that can only hold one character.

output[i] = `--${output[i]}--`;

You need to change it to something like this (code below may not work):

output = output.substring(0,i-1)   el   output.substring(i 1,output.length - i-1);

I recommend using the string.replaceAll function instead. If you create a loop yourself you'll get problems when adding more characters on a place where original one character was present.

function LetterCapitalize(str) {
  // code goes here
  let array = str.split(" ")
  for (let i=0; i<array.length; i  ){
    array[i] = array[i].charAt(0).toUpperCase()   array[i].slice(1)
  } 
  let output = array.join(" ") ;
  let comp = "vn52tqsd0e4a".split("");

  comp.map(el=> {
    output = output.replaceAll(el, '--'   el   '--');
  });
  console.log(output);

} 


LetterCapitalize("hello world");

  • Related