简体   繁体   中英

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?

You can use lookahead with (?=[1-9]) and (?=[az]) 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+(?=[az])/gi, ' ').replace(/\s+(?=[1-9])/gi, ' ').replaceAll('. ', '.'); console.log(result)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM