JavaScript Regular Expressions - Forcing case when replacing
Does the JavaScript regex standard support forcing case when doing a search/replace?
I am generally aware of the \u etc. options for forcing the case of a capture group in the replacement portion of a regular expression. I am unable to figure out how to do this in a JavaScript regex though. I do not have access to the JavaScript code itself but rather a program I am using allows entry of the regex strings which it passes through to t开发者_JAVA百科he regex engine itself.
If I understand you correctly, no.
You cannot evaluate javascript (to transform matches to uppercase) from within a regex pattern.
I'm only aware of str.replace() to convert to uppercase.
String Matching is done using regular expressions.String Replacement, however, only cares about what portion of the subject string you are replacing (which it is fed by the regular expression match), and it just does direct string replacement based on what you give it:
var subject = "This is a subject string";
// fails, case-sensitive match by default
subject.replace(/this/, "That");
// succeeds, case-insensitive expression using /i modifier, replaces the word "This" with the word "That"
subject.replace(/this/i, "That");
Now, if you wanted to capture a part of the matched string and use it to change the case, you can do that as well using expression groups (parentheses in your expression):
var subject = "This is a subject string";
var matches = subject.match(/(subject) string/i);
if (matches.length > 0)
{
// matches[0] is the entire match, or "subject string"
// matches[1] is the first group match, or "subject"
subject.replace(matches[1], matches[1].toUpperCase());
// subject now reads "This is a SUBJECT string"
}
In short, doing a match you can handle case-sensitivity if you wish. Doing a replacement is as simple as telling it what direct string to use for replacement.
JavaScript regular expressions are case sensitive by default and support case insensitivity if passed the /i
flag.
精彩评论