Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace initial spaces with underscores in Javascript

It's easy to replace spaces with (say) underscores:

y = x.replace(/ /g, '_');

It's also easy to remove leading spaces:

y = x.replace(/^ +/, '');

But is there a good way to replace only the initial spaces with underscores?

like image 300
Charles Avatar asked Apr 28 '26 06:04

Charles


2 Answers

T.J. Crowder's answer is definitely better than this method, but I thought I would add it because it's only a matter of time until lookbehinds are supported in all major browsers. At the time of writing this answer, the V8 engine shipped in Chrome 62 and XS (January 17, 2018 update) are the only implementations of variable length lookbehinds in JavaScript as per EMCA TC39's regexp lookbehind proposal.

Note the regex below contains a trailing space. If you have Chrome 62+ (or if you're in the future; another browser that supports variable length lookbehinds) you can test the regex here.

(?<=^ *) 

const regex = /(?<=^ *) /g
const str = '        something is here'

console.log(str.replace(regex, '_'))
like image 87
ctwheels Avatar answered Apr 29 '26 19:04

ctwheels


I want to replace each of the leading spaces with an underscore

To do that with just one replace call within the current spec,* you'd need the function call version of replace to do that, creating a string of underscores as long as the matched sequence of spaces:

y = x.replace(/^ +/, function(m) {
    return "_".repeat(m.length);
});

or with an ES2015+ arrow function:

y = x.replace(/^ +/, m => "_".repeat(m.length));

Live Example:

const x = "    four spaces";
const y = x.replace(/^ +/, m => "_".repeat(m.length));
console.log(y);

String.prototype.repeat was added in ES2015. If you need to support obsolete JavaScript engines, the MDN page has a polyfill you can use.


* But see ctwheels' answer using a feature from ES2018: Look-behinds. V. clever!

like image 26
T.J. Crowder Avatar answered Apr 29 '26 18:04

T.J. Crowder