Martin Comeau
Martin Comeau

Reputation: 21

How to select all multiple spaces except last two before a specific character with a Regex?

Here is an example string:

   Lorem ipsum   
         - dolor sit amet consectetur      
    - adipisicing elit. Adipisci, quam.     

What would be the most elegant regex to select all extra spaces EXCEPT for two spaces before the "-" to make an elegant list?

Here is an example desired result:

Lorem ipsum
  - dolor sit amet consectetur
  - adipisicing elit. Adipisci, quam.

Here is my best guess: / {2,}(?! {2}-)/g. Sadly, it also selects the two spaces before the "-".

Edit: I think I'll go with the folowwing:

let str = `       Lorem ipsum   
             - dolor sit amet consectetur      
        - adipisicing elit. Adipisci, quam.   `;
str = str.replace(/ {2,}/g, "");
str = str.replace(/-/g, "  -");
console.log(str);

Upvotes: 1

Views: 64

Answers (3)

Paul Lemarchand
Paul Lemarchand

Reputation: 2096

(^( +)[a-zA-Z])|(( +)(( {2}-)|\n|$))
  • (^( +)[a-zA-Z]): This group matches the characters before Lorem Ipsum.
  • (( +)(( {2}-)|\n|$)) This group matches the characters before two spaces and a -, or before a newline \n, or before the end of string $.

https://regex101.com/r/i4ppG7/5

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163277

You could select all spaces or tabs from the start and the end of the string and replace them with an empty string. Then replace the strings that start with a hyphen with 2 spaces.

const regex = /^[\t ]+|[\t ]+$/mg;
const str = `   Lorem ipsum
         - dolor sit amet consectetur
    - adipisicing elit. Adipisci, quam. `;
const subst = ``;
const result = str.replace(regex, subst).replace(/^-/gm, "  -");
console.log(result);

You could also you a combination of map and trim:

let str = `   Lorem ipsum
         - dolor sit amet consectetur
    - adipisicing elit. Adipisci, quam. `;
str = str.split("\n").map(s => s.trim()).map(x => x.replace(/^-/, "  -")).join("\n");
console.log(str);

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37755

You can use capturing group

let str = `Lorem ipsum   
        - dolor sit amet consectetur      
  - adipisicing elit. Adipisci, quam.  `

let finalList = str.replace(/^\s*(\s{2}.*)$/gm, '$1')

console.log('original list\n',str)
console.log('New list\n',finalList)

Upvotes: 0

Related Questions