简体   繁体   English

JavaScript正则表达式替换一系列字符

[英]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. ie:第一个#之前的字符串开头的所有空格和最后一个#之后的所有空格,其他一切(包括字符串中间的空格)保持不变。

My initial thinking was to use two Reg Exp, one for each part of the problem. 我最初的想法是使用两个Reg Exp,每个问题都有一个。

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. 但是,我无法获得第一个,我不确定是否有可能使用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. 这在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. 使用ECMAScript 6,您可以使用/[ ]/y ,这将要求匹配相邻,因此您可以逐个匹配空格,但要确保不要超过第一个非空格。 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: 对于ECMAScript 5(可能与您更相关),最简单的方法是使用替换回调:

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. 我删除了这个答案,因为它显然没有回答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! 只需用下划线替换捕获组即可!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM