5
var str = '  Some string    ';
var output = str.replace(/^\s|\s(?=\s*$)/g , '_');

The output should look like this

'___Some string____'

This code works fine for the trailing whitespaces but all the leading whitespaces are replaced with just one underscore.

The working php regex for this is: /\G\s|\s(?=\s*$)/

4 Answers 4

7

Not pretty, but gets the job done

var str = "  Some string    ";
var newStr = str.replace(/(^(\s+)|(\s+)$)/g,function(spaces){ return spaces.replace(/\s/g,"_");});
Sign up to request clarification or add additional context in comments.

5 Comments

this is good work! And imo the only useful, since Js sadly does not support lookbehind.
Brilliant, I knew there was a clever way to create the replacement string.
This works! It's weird that the php pattern could not be adapted for JS.
It could not be adapted since JavaScript does not support lookbehinds.
+1 but the expression can be simplified to just: /^\s+|\s+$/g. There's no need for any of the capture groups (which aren't being used anyway - the first parameter passed to the callback function is the whole match: i.e. spaces == $0).
1

This works but I don't like it:

var str = "  some string  ";
var result = str.replace(/^\s+|\s+$/g, function(m) {
    return '________________________________________'.substring(0, m.length);
});

Or more flexibly:

var str = "  some string  ";
var result = str.replace(/^\s+|\s+$/g, function(m) {
    var rv = '_',
        n;
    for (n = m.length - 1; n > 0; --n) {
        rv += '_';
    }
    return rv;
});

That can be refined, of course.

But I like epascarello's answer better.

1 Comment

@epascarello: I refer you to my opening sentence. :-)
0

another reg ex

var str = "  asdf       "
str.replace(/^[ ]+|[ ]+$/g,function(spc){return spc.replace(/[ ]/g,"_")})
//"__asdf_______" 

Comments

0

With String.prototype.repeat() the accepted answer can now be improved to

function replaceLeadingAndTrailingWhitespace(text, replace) {
    return text.replace(/^\s+|\s+$/g, (spaces) => replace.repeat(spaces.length));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.