简体   繁体   中英

JavaScript regular expression to replace a sequence of chars

I want to replace all spaces in the beginning and the end of a string with a underscore in this specific situation:

var a = '   ## ## #  ';
console.log(myReplace(a)); // prints ___## ## #__

ie: all the spaces in the beginning of the string before the first # and all the spaces after the last #, everything else (including spaces in the middle of the string) remains untouched.

My initial thinking was to use two Reg Exp, one for each part of the problem.

However, I couldn't get the first one and I'm not sure if it's even possible to do what I want using JS regexp.

str.replace(/^\ /g, '_'); // replaces only the first space
str.replace(/^\ +/, '_') //  replaces all the correct spaces with only one underscore

Thanks!

You have to use a callback function:

var newStr = str.replace(/(^( +)|( +)$)/g, function(space) { 
                             return space.replace(/\s/g,"_");
                           }
                         );

Try this:

var result = str.replace(/^ +| +$/g,
             function (match) { return new Array(match.length+1).join('_'); });

This one is tough in JavaScript. With ECMAScript 6, you could use /[ ]/y which would require the matches to be adjacent, so you could match spaces one-by-one but make sure that you don't go past the first non-space. For the end of the string you can (in any case) use /[ ](?=[ ]*$)/ .

For ECMAScript 5 (which is probably more relevant to you), the easiest thing would be to use a replacement callback:

str = str.replace(
    /^[ ]+|[ ]+$/g,
    function(match) {
        return new Array(match.length + 1).join("_");
    }
);

This will programmatically read the number of spaces and write back just as many underscores.

I deleted this answer, because it evidently doesn't answer the question for JavaScript. I'm undeleting it so future searchers can find a regexy way to get whitespace at the ends of strings.

this doesn't correctly answer your question, but might be useful for others

This regex will match all whitespace at the beginning and end of your string:

^(\s*).*?(\s*)$

Just replace the capturing groups with underscores!

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