Javascript replace() with case-change

后端 未结 2 555
别那么骄傲
别那么骄傲 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); 
      })
      
      0 讨论(0)
    • 2020-12-19 10:16

      easiest is probably to use a regex match and then use .toUpperCase on the match. I modified the regex slightly to add in a second capture group

      var str = '<li>something</li>';
      var arr = /<([\w]+)([^>]*>.*?<\/)\1>/.exec(str);
      str = '<' + arr[1].toUpperCase() + arr[2] + arr[1].toUpperCase() + '>';
      
      0 讨论(0)
    提交回复
    热议问题