Javascript string replace method. Using matches in replacement string

六眼飞鱼酱① 提交于 2021-02-15 07:52:26

问题


I have the following javascript string

/Library/Application%20Support/Adobe/Fireworks%20CS6/Commands

The numeral in the "CS#" section may change, but I would like to convert the string to the following format keeping in mind that the numeral may change.

/Library/Caches/Adobe/TypeSupport/CS6

I know I can do this in several ways, but for the purpose of education I am looking for the best method.

I can search with a regular expression using the replace method, but is it possible to use matches in the replacement?

Thanks for any help


回答1:


The simplest solution is to use parentheses in the regular expression to capture the part of the original string you wish to use in the replacement, and then include that in the replacement string via the special sequence $1. For your example:

'/Library/Application%20Support/Adobe/Fireworks%20CS6/Commands'.replace(
    /^.*\/(CS[0-9]+).*$/, 
    '/Library/Caches/Adobe/TypeSupport/$1'); 
// => /Library/Caches/Adobe/TypeSupport/CS6

(You can have more than one set of parentheses, in which case subsequent groups are $2, $3, etc. Sometimes the string you care about happens to be exactly what matches the entire regular expression, in which case you can just use $& in the replacement string , and don't need any parentheses.)

This is great for simply including literal text from the source string, as you're doing.

If you're doing anything a bit fancier, however - such as trying to change the case of the matched text - it won't work. ('$1'.toLowerCase() will simply convert the literal string '$1' to lowercase before passing it to replace; not helpful.) For those situations, you can use a function instead of a string as the replacement. It will be called once per match, and passed the part of the string that matched (equivalent to $& in the string version); if there are parentheses in the regex, it will be passed an additional parameter containing the match for each group, in order. So you could convert your example to lowercase like this:

'/Library/Application%20Support/Adobe/Fireworks%20CS6/Commands'.replace(
        /^.*\/(CS[0-9]+).*$/, 
        function(whole_match, cs_number) { 
          return "/Library/Caches/Adobe/type_support/" + cs_number.toLowerCase()
        });  
// => /Library/Caches/Adobe/type_support/cs6

You can read the Mozilla spec/documentation here.




回答2:


Sure :

'/Library/Application%20Support/Adobe/Fireworks%20CS6/Commands'.replace(/.*(CS[0-9]+).*/, '/Library/Caches/Adobe/TypeSupport/$1');

You can refer to capture groups using $N, where N is the index of the group (starting at 1).



来源:https://stackoverflow.com/questions/13390724/javascript-string-replace-method-using-matches-in-replacement-string

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