Plamen Draganov
Plamen Draganov

Reputation: 33

How to format a JavaScript string with replaceAll using regex

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?

Upvotes: 3

Views: 371

Answers (2)

anubhava
anubhava

Reputation: 785651

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])\s*\t|\s+$|\n(?=\d\.)/g, '$1');

console.log(r);

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

RegEx Breakup:

  • ([.\s])\s*\t: Match dot or a whitespace and capture in group #1 followed by 0+ whitespaces followed by a tab. We will put back this replacement using $1
  • |: OR
  • \s+$: Match 1+ whitespaces before end
  • |: OR
  • \n(?=\d\.): Match \n if it is followed by a digit and a dot

Upvotes: 3

Mina
Mina

Reputation: 17524

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)

Upvotes: 2

Related Questions