Skip to content Skip to sidebar Skip to footer

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 ___

Solution 1:

You have to use a callback function:

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

Solution 2:

Try this:

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

Solution 3:

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) {
        returnnewArray(match.length + 1).join("_");
    }
);

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

Solution 4:

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!

Post a Comment for "Javascript Regular Expression To Replace A Sequence Of Chars"