Javascript replace() with case-change

后端 未结 2 566
别那么骄傲
别那么骄傲 2020-12-19 09:20

Is there an easy way to change the case of a matched string with javascript?

Example

String :

  • something
  • <
    2条回答
    •  没有蜡笔的小新
      2020-12-19 10:10

      You can pass the replace method a replacer function. The first argument for which is the whole match, the second will be $1. Thus:

      mystring.replace(/<([\w]+)[^>]*>.*?<\/\1>/, function(a,x){ 
         return a.replace(x,x.toUpperCase()); 
      })
      

      although this form saves the extra operation by making an additional capture (should be faster but haven't checked):

      mystring.replace(/<([\w]+)([^>]*>.*?<\/\1>)/, function(a,x,y){ 
         return ('<'+x.toUpperCase()+y); 
      })
      

    提交回复
    热议问题