I have participated in several written tests for front-end intern recruitment recently and found that many written test questions will test string processing, such as Qunar.com written test questions, Taobao written test questions, etc. If you often take written exams or have been there, I believe you, like me, will find that string processing is one of the most common question types in the front-end recruitment process.
These questions have one characteristic. Consider it from the examiner's perspective. It tests not whether you know it, but whether you can use it more concisely without borrowing XX manual or XX guide or Baidu and Google. Write the answer in the following way.
Unfortunately, many developers, of course I am one of them, cannot firmly remember their usage for many frequently used string processing functions, and always have to turn to the XX manual or XX guide for help. Or Baidu Google.
The result of this is that these very critical basic knowledge are not strong enough. When encountering these questions, you have to use N-level nested for loops to traverse them one by one.
This is a signal. When you find that you are using too many for loops when doing this type of questions, then pay attention. It is very likely that you have written incorrectly. Don't underestimate these things, they may play a big role in finding a job and daily development.
Okay, no more talk, let’s summarize them one by one. It is inevitable that there will be some omissions. If you happen to find them, please feel free to add them or send a private message.
1. String conversion
String conversion is the most basic requirement and work. You can convert any type of data into a string. You can use any of the following three methods:
var num= 19; // 19 var myStr = num.toString(); // "19"
You can also do this:
var num= 19; // 19 var myStr = String(num); // "19"
Or, even simpler:
var num= 19; // 19 var myStr = "" +num; // "19"
2. String segmentation
String splitting is to split a string into multiple strings. JavaScript provides us with a very convenient function, such as:
var myStr = "I,Love,You,Do,you,love,me"; var substrArray = myStr .split(","); // ["I", "Love", "You", "Do", "you", "love", "me"]; var arrayLimited = myStr .split(",", 3); // ["I", "Love", "You"];
The second parameter of split() indicates the maximum length of the returned string array.
3. Get the string length
String length is often used in development. It is very simple as follows:
var myStr = "I,Love,You,Do,you,love,me"; var myStrLength = myStr.length; //25
4. Query substring
Many people will forget these JavaScript’s built-in methods, or forget their specific usage, resulting in having to nest a for loop when doing the questions.
The first function: indexOf(), it searches from the beginning of the string and returns the corresponding coordinates if found. If not found, it returns -1. As follows:
var myStr = "I,Love,you,Do,you,love,me"; var index = myStr.indexOf("you"); // 7 ,基于0开始,找不到返回-1
The second function: lastIndexOf(), it searches from the end of the string and returns the corresponding coordinates if found. If not found, it returns -1. As follows:
var myStr = "I,Love,you,Do,you,love,me"; var index = myStr.lastIndexOf("you"); // 14
The above two functions also receive a second optional parameter, indicating the starting position of the search.
5. String replacement
Just finding a string shouldn’t stop. In general questions, you will often be asked to find and replace it with your own string, for example:
var myStr = "I,love,you,Do,you,love,me"; var replacedStr = myStr.replace("love","hate");//"I,hate,you,Do,you,love,me"
By default, only the first found one is replaced. If you want to replace it globally, you need to put a regular global flag, such as:
var myStr = "I,love,you,Do,you,love,me"; var replacedStr = myStr.replace(/love/g,"hate"); //"I,hate,you,Do,you,hate,me"
For more detailed explanations, please refer to: http://www.w3school.com.cn/jsref/jsref_replace.asp
6. Find the character at a given position or its character encoding value
To find a character at a given position, you can use the following function:
var myStr = "I,love,you,Do,you,love,me"; var theChar = myStr.charAt(8);// "o",同样从0开始
Similarly, one of its sibling functions is to find the character encoding value of the corresponding position, such as:
var myStr = "I,love,you,Do,you,love,me"; var theChar = myStr.charCodeAt(8); //111
7. String concatenation
The string concatenation operation can be as simple as using an addition operator, such as:
var str1 = "I,love,you!"; var str2 = "Do,you,love,me?"; var str = str1 + str2 + "Yes!";//"I,love,you!Do,you,love,me?Yes!"
Similarly, JavaScript also comes with related functions, such as:
var str1 = "I,love,you!"; var str2 = "Do,you,love,me?"; var str = str1.concat(str2);//"I,love,you!Do,you,love,me?"
The concat() function can have multiple parameters, pass multiple strings, and splice multiple strings.
8. String cutting and extraction
There are three ways to extract and cut from strings, such as:
The first method is to use slice():
var myStr = "I,love,you,Do,you,love,me"; var subStr = myStr.slice(1,5);//",lov"
Second, use substring():
var myStr = "I,love,you,Do,you,love,me"; var subStr = myStr.substring(1,5); //",lov"
The third method is to use substr():
var myStr = "I,love,you,Do,you,love,me"; var subStr = myStr.substr(1,5); //",love"
Different from the first and second methods, the second parameter of substr() represents the maximum length of the intercepted string, as shown in the above results.
9. String case conversion
Commonly used functions for converting to uppercase or lowercase strings are as follows:
var myStr = "I,love,you,Do,you,love,me"; var lowCaseStr = myStr.toLowerCase();//"i,love,you,do,you,love,me"; var upCaseStr = myStr.toUpperCase();//"I,LOVE,YOU,DO,YOU,LOVE,ME"
10. String matching
String matching may require you to have a certain understanding of regular expressions. Let’s take a look at the match() function first:
var myStr = "I,love,you,Do,you,love,me"; var pattern = /love/; var result = myStr.match(pattern);//["love"] console.log(result .index);//2 console.log(result.input );//I,love,you,Do,you,love,me
如你所见,match()函数在字符串上调用,并且接受一个正则的参数。来看看第二个例子,使用exec()函数:
var myStr = "I,love,you,Do,you,love,me"; var pattern = /love/; var result = pattern .exec(myStr);//["love"] console.log(result .index);//2 console.log(result.input );//I,love,you,Do,you,love,me
简单吧,仅仅是把正则和字符串换了个位置,即exec()函数是在正则上调用,传递字符串的参数。对于上面两个方法,匹配的结果都是返回第一个匹配成功的字符串,如果匹配失败则返回null.
再来看一个类似的方法search(),如:
var myStr = "I,love,you,Do,you,love,me"; var pattern = /love/; var result = myStr.search(pattern);//2
仅返回查到的匹配的下标,如果匹配失败则返回-1.
11、字符串比较
比较两个字符串,比较是规则是按照字母表顺序比较的,如:
var myStr = "chicken"; var myStrTwo = "egg"; var first = myStr.localeCompare(myStrTwo); // -1 first = myStr.localeCompare("chicken"); // 0 first = myStr.localeCompare("apple"); // 1
12、举例
最后我们来看一道前端笔试题,去哪儿网的,相信很多孩子都做到过这个题了。题目:写一个getSuffix函数,用于获得输入参数的后缀名,例如输入abcd.txt,返回txt。附上我的答案:
function getSuffix(file){ return file.slice(file.lastIndexOf(".") + 1,file.length); }
结束语
相信JavaScript中字符串操作的函数应该不止这几个,但是上面列的这些应该都是非常常用的。如果有哪些需要补充的,欢迎补充!希望看到这些以后,再面对字符串的笔试面试题你能非常从容的面对。