![]() ![]() It is the combination of the 3 solutions above and these byte saving measures that is how we get the code at the top of this post. ![]() We can also leverage our variable 'a' since it's prototype includes a reference to we can swap that out with a.toUpperCase. This means that we can substitute in String.call for (actually we can use Date.call to save even more bytes but that's less semantic). The replace () method returns a new string with a substring ( substr) replaced by a new one ( newSubstr ), while leaving the invoking string unchanged. The String constructor, being a function, inherits from Function's prototype. Instead we'll leverage the fact that we have objects that reference the same methods via inheritance. Nobody wants to type prototype a bunch of times. We have now arrived at working code! a.replace(/f/, ()) Luckily, we can simply substitute in () (which accepts any number of arguments, none of which have type restrictions) for (). Replace a Regex capture group with uppercase in Javascript - Stack Overflow Replace a Regex capture group with uppercase in Javascript Ask Question Asked 12 years, 1 month ago Modified 1 year, 5 months ago Viewed 73k times 108 I'd like to know how to replace a capture group with its uppercase in JavaScript. This would cause an invalid argument list error. However, () expects the second parameter to be an array but instead gets either a string or number (depending on if you use capture groups or not). The last issue is that () will pass several arguments to its replacement function. We now have the following a.replace('f', ()) Using () we can create a copy of with its context specifically set to. How does it know to run () on ()? Solution 2 Which is obviously not what we have intended. The replacerFunction is used to create a substring to replace the match. The second argument of the replace () method can be a function like this: replace (regexp, replacerFunction) The replace () method calls the replacerFunction after it finds the first match. So what we are actually doing looks more like this a.replace('f', ) JavaScript regex replace () method with replacer function. This is because is actually a reference to () via JavaScript's prototypical inheritance. If you attempt to run the code now you will get an error stating that undefined is not a function and therefore cannot be called. Simply removing the parameters and parentheses will give us a reference rather than executing the function. So where did you go wrong and what is this new voodoo? Problem 1Īs stated before, you were attempting to pass the results of a called method as the second parameter of (), when instead you ought to be passing a reference to a function Solution 1 I know I'm late to the party but here is a shorter method that is more along the lines of your initial attempts. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |