Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

javascript - I want to count a same letter if the previous letter is the same as the current letter

I have the input string "lorrem ipsssum dollorrrrum" and I want to count the same letter if the current letter is the same as the previous letter and change all the next same letter to the counted that letter,

I want the exact result to look like this:

"lor2emips3umdol2or4um"

I am stuck and I don't know what algorithm should I use, and what keyword to search about this issue in Google :(

The code I've written so far

function countLetter(str) {
    return str
        .replace(/s/g, '')
        .split('')
        .reduce((a, b) => {
            return a === b ? b.replace(b, '') : b;
        });
}

window.onload = function () {
  console.log(countLetter('lorrem ipsssum dollorrrrum'));
}
question from:https://stackoverflow.com/questions/65892494/i-want-to-count-a-same-letter-if-the-previous-letter-is-the-same-as-the-current

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With a regular expression, you can capture a character and then backreference that same character 1 or more times. Use a replacer function to replace the matched section with the character and the number of characters in the full match:

function countLetter(str) {
    return str
        .replace(/s/g, '')
        .replace(/(w)1+/g, (match, char) => char + match.length);
}

console.log(countLetter('lorrem ipsssum dollorrrrum'));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...