JavaScript regular expression to replace a sequence of chars

久未见 提交于 2021-02-10 08:42:15

问题


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 ___## ## #__

i.e.: 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!


回答1:


You have to use a callback function:

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



回答2:


Try this:

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



回答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) {
        return new Array(match.length + 1).join("_");
    }
);

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




回答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!



来源:https://stackoverflow.com/questions/18494868/javascript-regular-expression-to-replace-a-sequence-of-chars

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!