Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
adding indicators into a string according to different case

I will receive an array of string-like below.
In each string, there may be three signs: $,%,* in the string

For example,
“I would $rather %be $happy, %if working in a chocolate factory”
“It is ok to play tennis”
“Tennis $is a good sport”
“AO is really *good sport”
However, there may be no signs in it, maybe only one sign in it.

There are only five cases in string,
1. no sign at all,
2. having $,% ;
3. having only $,
4 having only %,
5 having only *

If there is no sign, I don’t need to process it.
Otherwise, I need to process it and add an indicator to the left of the first sign that occurs in the sentence.

For example:
“I would ---dollorAndperSign—-$rather %be $happy, %if working in a chocolate factory”
“Tennis --dollorSign—-$is a good sport”

This is my idea code.

So, I need to decide if the string contains any sign. If there is no sign, I don’t need to process it.

texts.map((text) => {
  if (text.includes("$") || text.includes("%") || text.includes("*")) {
    //to get the index of signs
    let indexOfdollar, indexOfper, indexOfStar;
    indexOfdollar = text.indexOf("$");
    indexOfper = text.indexOf("%");
    indexOfStar = text.indexOf("*");

    //return a completed process text
  }
});

Question:

how do I know which index is the smallest one in order to locate the position of the first sign occurring in the text? Getting the smallest value may not be the correct approach coz there may be the case that I will get -1 from the above code?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

I focussed only on the "get the smallest index" part of your question... Since you will be able to do what you want with it after.

You can have the indexOf() in an array, filter it to remove the -1 and then use Math.min() to get the smallest one.

Edited to output an object instead, which includes the first index and some booleans for the presence each char.

const texts = [
  "I would $rather %be $happy, %if working in a chocolate factory",
  "It is ok to play tennis",
  "Tennis $is a good sport",
  "AO is really *good sport"
]

const minIndexes = texts.map((text,i) => {
  //to get the signs
  const hasDollard = text.indexOf("$") >= 0
  const hasPercent = text.indexOf("%") >= 0
  const hasStar = text.indexOf("*") >= 0
  
  //to get the first index
  const indexes = [text.indexOf("$"), text.indexOf("%"), text.indexOf("*")].filter((index) => index >= 0)
  if(!indexes.length){
    return null
  }
  return {
   index: Math.min( ...indexes),
   hasDollard,
   hasPercent,
   hasStar
 }
});

console.log(minIndexes)

about 4 years ago · Juan Pablo Isaza Relatório

0

You could find the special characters and replace the first found with a text.

const
    replace = s => {
        const
            signs = { $: 'dollar', '%': 'per', '*': 'star' },
            characters = s.match(/[\$\%\*]/g)?.join('') || '',
            text = Array
                 .from(
                     new Set(Array.from(characters)),
                     c => signs[c]
                )
                .join('And') + 'Sign';

        return s.replace(/[\$\%\*]/, `--${text}--$&`);
    },
    data = ['I would $rather %be $happy, %if working in chocolate factory', 'It is ok to play tennis', 'Tennis $is a good sport', 'AO is really *good sport'],
    result = data.map(replace);

console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

const texts = [
  "I would $rather %be $happy, %if working in a chocolate factory",
  "It is ok to play tennis",
  "Tennis $is a good sport",
  "AO is really *good sport"
]

texts.forEach(text => {
  let sighs = ["%","$","*"];
  let chr = text.split('').find(t => sighs.find(s => s==t));
  if (!chr)
    return;
    
  text = text.replace(chr, "---some text---" + chr);
  console.log(text);
})

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda