Home > Software engineering >  How to format a JavaScript string with replaceAll using regex
How to format a JavaScript string with replaceAll using regex

Time:09-19

I am trying to format a kind of a board game notation which consists of tabs and spaces. The original string is looking like this:

1.    \td11-d9    \te7-e10    \n2.    \ta8-c8    \tg7-g10xf10    \n3.    \th11-h9    \tf7-i7    

I used this replace method to clean up all of the tabs and new lines

string.replace(/\s\s /g, ' ').replaceAll('. ', '.');

So, after that the string is looking like this:

1.d11-d9 e7-e10 2.a8-c8 g7-g10xf10 3.h11-h9 f7-i7

However, I want to add more space before the number with the dot. So, the string must look like this with 3 spaces before the number of the move (the number with the dot):

1.d11-d9 e7-e10   2.a8-c8 g7-g10xf10   3.h11-h9 f7-i7

Can I also make all of these operations with a one line code or just one JavaScript method?

CodePudding user response:

You can use lookahead with (?=[1-9]) and (?=[a-z]) to check if the number add two spaces, and if a letter just add one space.

const string = `1.    \td11-d9    \te7-e10    \n2.    \ta8-c8    \tg7-g10xf10    \n3.    \th11-h9    \tf7-i7`

const result = string.replace(/\s (?=[a-z])/gi, ' ').replace(/\s (?=[1-9])/gi, '  ').replaceAll('. ', '.');

console.log(result)

CodePudding user response:

Here is how you can do this in a single .replace call:

const s = "1.    \td11-d9    \te7-e10    \n2.    \ta8-c8    \tg7-g10xf10    \n3.    \th11-h9    \tf7-i7    ";

var r = s.replace(/\s*\t|\s $|\n(?=\d\.)/g, '');

console.log(r);

//=> "1.d11-d9e7-e10    2.a8-c8g7-g10xf10    3.h11-h9f7-i7"

RegEx Breakup:

  • \s*\t: Match 0 whitespaces followed by a tab
  • |: OR
  • \s $: Match 1 whitespaces before end
  • |: OR
  • \n(?=\d\.): Match \n if it is followed by a digit and a dot
  • Related