Reputation: 21
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
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
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
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