简体   繁体   中英

regex replace leading spaces in text line

I have a string:

"    Some text here\n   Some new line text here"

I need to get from it:

"----Some text here\n---Some new line text here"

So that each space in the beginning of the line (string or line break symbol) would be replaces with say dash.

Not sure how to implement it the simplest way.

Try following:

> "    Some text here\n   Some new line text here".replace(/^\s+/gm, '----')
"----Some text here\m----Some new line text here"

or:

"    Some text here\n   Some new line text here".replace(/^\s+/gm, function(spaces) { return spaces.replace(/./g, '-'); } )
"----Some text here\m----Some new line text here"

There is a way to match each leading pattern individually using a lookbehind, but this is an ECMAScript 2018+ only compatible solution.

Lookbehind adoption can be tracked here , see RegExp Lookbehind Assertions . Right now, they are supported by Chrome, Edge, Opera including Opera Mobile, Samsung Internet, and Node.js. Firefox is adding "support for the dotAll flag, lookbehind references, named captures, and Unicode escape sequences" to the SpiderMonkey RegExp engine on June 30, 2020.

Solution for the current scenario:

.replace(/(?<=^\s*)\s/gm, '-')

Here, /(?<=^\\s*)\\s/gm matches any whitespace char ( \\s ) that is immediately preceded with any 0+ whitespace chars at the start of the line (see the (?<=^\\s*) positive lookbehind). See this regex demo .

NOTE : since \\s matches line break chars, all empty lines will be replaced with a hyphen, too. If empty lines must be preserved use [^\\S\\n\\v\\f\\r\
\
 instead of \\s :

.replace(/(?<=^[^\S\n\v\f\r\u2028\u2029]*)[^\S\n\v\f\r\u2028\u2029]/gm, '-')

where [^\\S\\n\\v\\f\\r\
\
] matches any whitespace char other than linefeed, vertical tab, form feed, carriage return, line and paragraph separators. See this regex demo .

JS demo:

 // Any whitespace chars console.log(" Some text here\\n\\n Some new line text here" .replace(/(?<=^\\s*)\\s/gm, '-')) // Only horizontal whitespace console.log(" Some text here\\n\\n Some new line text here" .replace(/(?<=^[^\\S\\n\\v\\f\\r\
\
]*)[^\\S\\n\\v\\f\\r\
\
]/gm, '-'))

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