Javascript replace () with case replacement

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

Example

Line: <li>something</li>

Regex: /<([\w]+)[^>]*>.*?<\/\1>/

And what I would like to do is replace the $ 1 match with all the uppercase letters (inside the substitution, if possible). I'm not quite sure when $ 1 is a valid match, not a string - '$ 1'.toUpperCase does not work.

So how can I come back <li>something</li>? A method, not a regular expression.

+4
source share
2 answers

You can pass the replacement function to the replacement method. The first argument for which is the whole match, the second will be $ 1. In this way:

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

, ( , ):

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

, .toUpperCase . , .

var str = '<li>something</li>';
var arr = /<([\w]+)([^>]*>.*?<\/)\1>/.exec(str);
str = '<' + arr[1].toUpperCase() + arr[2] + arr[1].toUpperCase() + '>';
0

All Articles