Home > OS >  Regex to reduce repeating characters with spaces to single character
Regex to reduce repeating characters with spaces to single character

Time:01-18

Find a repeating character with or without spacing between them and reduce it to a single character.

Reduce { character

Sample 1

Hello { {

Result 1

Hello {

Sample 2

Hi {{ { text

Result 2

Hi { text

Sample 3

Other { { {{ text

Result 3

Other { text

CodePudding user response:

EDIT - rereading the question, I realise this doesn't fully answer the question as it does not find the character. I will leave this answer up as its a start...

You could write a function that takes the text and the character to remove, using replace() with a regex pattern to substitute any occurrence of one or more repetitions of the character with a single instance of the character.

function reduceRepeatingCharacters(text, char) {
    // Use the regex pattern to match the repeating character
    const pattern = new RegExp(char   " ", "g");
    return text.replace(pattern, char);
}

// Test the function with the given samples
let text1 = "Hello { {";
console.log(reduceRepeatingCharacters(text1, "{"));
// Output: Hello {

let text2 = "Hi {{ { text";
console.log(reduceRepeatingCharacters(text2, "{"));
// Output: Hi { text

let text3 = "Other { { {{ text";
console.log(reduceRepeatingCharacters(text3, "{"));
// Output: Other { text

CodePudding user response:

If you want the function to be generalized for any character, without the need to specify the character yourself, you can use the following:

function reduceRepeatingCharacters(text) {
  // Use the regex pattern to match the repeating character
  const pattern = /[ \t] (.)([ \t]*\1[ \t]*?) /g
  return text.replace(pattern, " $1");
}

Note the pattern above includes ALL characters repetitions, meaning also letters outside of a word, as well as repetitions of multiple characters in the same line:

console.log(reduceRepeatingCharacters("Hi || | text"))
//Output: Hi | text

console.log(reduceRepeatingCharacters("Other $ $ $$ text"))
//Output: Other $ text

console.log(reduceRepeatingCharacters("Other $$$$ text"))
//Output: Other $ text

console.log(reduceRepeatingCharacters("Mamma aa aaa text"))
//Output: Mamma a text

console.log(reduceRepeatingCharacters("bubbi { { && && &     && text"))
//Output: bubbi { & text
  • Related