


Summary of common string manipulation functions and usage in JavaScript_javascript skills
The examples in this article summarize the common string manipulation functions and usage in JavaScript. Share it with everyone for your reference. The specific analysis is as follows:
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. There is one characteristic of these questions. Consider it from the examiner's perspective. It tests not whether you know it, but whether you can write it in a relatively concise way without borrowing XX manual or XX guide or Baidu and Google. Come up with the answer. It is a pity that many developers, of course I am one of them, cannot firmly remember their usage for many frequently used string processing functions, and they always have to turn to XX manual or XX guide or Baidu Google. . The result of this is that these very critical basic knowledge are not solid 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, be careful. 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.jb51.net/w3school/js/jsref_replace.htm
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中字符串操作的函数应该不止这几个,但是上面列的这些应该都是非常常用的。如果有哪些需要补充的,欢迎补充!希望看到这些以后,再面对字符串的笔试面试题你能非常从容的面对。
希望本文所述对大家的javascript程序设计有所帮助。

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools