Home > database >  Delete a Character from Every Word in a String Except One Certain
Delete a Character from Every Word in a String Except One Certain

Time:10-27

So I need to remove for example the letter "a" from every word in a string which is an element of array, except the word "an"

var arr = ['sentence example', 'an element of array', 'smth else']
var removedPuncts = []
for (i = 0; i < arr.length; i  ) {
  if (sentences.indexOf("an")) {
    ...
  }
}
console.log(removedPuncts)
//expected output: ['sentence exmple', 'an element of rry', 'smth else']

So maximum I thought it'll be needed to find an's index, but don't have an idea what to do next.

CodePudding user response:

Use a regular expression - match a with negative lookahead for n.

const arr = ['sentence example', 'an element of array', 'smth else'];
const output = arr.map(str => str.replace(/a(?!n)/g, ''));
console.log(output);

CodePudding user response:

const arr = ['sentence example', 'an element of array', 'smth else'];
let out = []
for (i = 0; i < arr.length; i  ) {
    let text = ""
    for (j = 0; j < arr[i].split(" ").length; j  ) {
        if (arr[i].split(" ")[j] == "an") {
            text  = "an"
        } else {
            text  = " "   arr[i].split(" ")[j].replaceAll('a', '')
        }
    }
    out.push(text)
}
console.log(out)
  • Related