This article starts with a simple string interview question and records some methods for manipulating strings, focusing on the details.
Recently, I encountered an interview question that I found interesting. Although it is simple, it is thought-provoking. The question is as follows: write a method to convert a string to camel case, for example: border.bottom.color -> borderBottomColor.
Manipulating String Arrays#
Most people should be able to write this method, which processes the string and concatenates it into a new string. It mainly tests several APIs of strings, using charAt(n) to get the character at the nth index of the string, or using array indexing ([]) to retrieve it.
function tranformStr(str) {
var strArr = str.split(".");
for (var i = 1; i < strArr.length; i++) {
strArr[i] = strArr[i].charAt(0).toUpperCase() + strArr[i].substring(1);
}
return strArr.join("");
}
Regular Expressions#
The second method uses regular expressions, which is actually a combination of the string's replace method and regular expressions. The difficulty lies mainly in understanding the replace method.
function transformStr(str) {
var re = /\.(\w)/g;
return str.replace(re, function(match, p1) {
return p1.toUpperCase();
});
}
From the above two methods, it can be seen that using regular expressions requires less code, but it also requires a higher understanding of regular expressions and the usage of the replace method. Below is a summary of some APIs of the replace method for strings.
Usage of replace#
str.replace(regexp|substr, newSubStr|function)
The first parameter of the replace method can be a regular expression or a string.
- regexp (pattern)
A regular expression (RegExp) object or its literal. The content matched by this regular expression will be replaced by the return value of the second parameter.
- substr (pattern)
A string to be replaced by newSubStr. It is treated as a whole string, not a regular expression. Only the first match will be replaced.
The second parameter of the replace method can be a string or a function.
- newSubStr (replacement)
A string used to replace the matched part of the first parameter in the original string. This string can interpolate some special variable names. Refer to the usage of strings as parameters below.
- function (replacement)
A function used to create a new substring, and the return value of this function will replace the result matched by the first parameter. Refer to specifying a function as a parameter below.
The replace method does not change the string itself that calls it, but only returns a new replaced string. When performing global search and replace, the regular expression must include the g flag.
Using a string as a parameter#
When the second parameter is a string, the replacement string can insert the following special variable names:
Variable Name | Represents |
---|---|
$$ | Inserts a "$". |
$& | Inserts the matched substring. |
$` | Inserts the content to the left of the currently matched substring. |
$' | Inserts the content to the right of the currently matched substring. |
$n | If the first parameter is a RegExp object and n is a non-negative integer less than 100, |
it inserts the string matched by the nth capturing group. |
The specific usage of special variable names is as follows:
"border.bottom.color".replace(/\.(\w)/g, "$$");
// border$ottom$olor
"border.bottom.color".replace(/\.(\w)/g, "$&");
// border.bottom.color
"border.bottom.color".replace(/\.(\w)/g, "$`");
// borderborderottomborder.bottomolor
"border.bottom.color".replace(/\.(\w)/g, "$1");
// borderbottomcolor
Specifying a function as a parameter#
When the second parameter is a function, in this case, the function will be executed after the match is performed. The return value of the function will be used as the replacement string. (Note: the special replacement parameters mentioned above cannot be used here.) Also, if the first parameter is a regular expression and it has the global matching mode, this method will be called multiple times, and each match will be called.
Variable Name | Represents |
---|---|
match | The matched substring. (corresponds to $& mentioned above) |
p1, p2, ... | If the first parameter of the replace() method is a RegExp object, it represents the string |
matched by the nth capturing group. (corresponds to $1, $2, etc. mentioned above) | |
offset | The offset of the matched substring in the original string. |
(For example, if the original string is "abcd" and the matched substring is "bc", | |
then this parameter will be 1) | |
string | The original string being matched. |
Note: The exact number of parameters depends on whether the first parameter of replace() is a regular expression object and how many parentheses substrings are specified in the regular expression.
In the original question at the beginning of the article, we need to match the first letter after a dot and replace it with an uppercase letter. The specific implementation code is as follows:
function transformStr(str) {
var re = /\.(\w)/g;
return str.replace(re, function(match, p1) {
return p1.toUpperCase();
});
}
First, declare a regular expression re that matches a dot followed by a parenthesis. This parenthesis is called a capturing parenthesis, and the matched content will be remembered for use in the second parameter. \w inside the capturing parenthesis matches a single word character (letter, number, or underscore), which is equivalent to [A-Za-z0-9]. The second parameter is a function, and the first string match is the matched string each time, which is .b and .c in the above example. p1 corresponds to the first string matched by the parenthesis, which is b and c. Inside the function, p1 is converted to uppercase because replace generates a completely new string, so it needs to be returned.