How to remove specific words on a string (and add the word "and" if possible) that are repeated twice but only twice and only certain characters?
Example: "Intruction in seated LE AROM x10 each instruction in standing LE AROM x10 each".
I want it to say, "Instruction in seated LE AROM and standing LE AROM x10 each".
I have tried looping through it and removing duplicates, but it removes duplicates that I do need. I also tried this that I found from somebody else’s question, but they were just wanting to count how many times a word was repeated, so it didn’t help me much.
function removeDuplicate(str) {
let words = JSON.stringify(str).toLowerCase().split(' ')
let wordsCount = {}
words.forEach(word => {
wordsCount[word] = (wordsCount[word] || 0) + 1
})
}
2
Answers
You can easily cout the occurrence of a word in a string then access a word via key or value.
Then select the words you want to keep or not in an
if(){}else{}
statement or aswitch
statement.It’s unclear to know the words what you want to keep and appears more than one time in the Array.
So here is a counter of occurrences then you’ll have to delete some words in the Array arrToChange depending of your conditions and convert the Array to String again.
Now you can count the number of occurrences and delete the words you want in Array arrToChange with the help of the method
findIndex()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
The example you give is not consistent with your explanations.
Why is "Instruction" removed only once, whereas ‘x10’ and ‘each’ are removed twice? What ‘and’ is supposed to replace exactly?
If you just want to replace "x10 each" with "and", there’s a build in JavaScript method doing this:
If you want to replace some words appearing twice with end, you can achieve this using
filter
andincludes
methods:But it seems that you ask for something else.