Common string manipulation functions and usage in JavaScript
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 are the same You can do this:
var num= 19; // 19 var myStr = String(num); // "19"
Or, even simpler:
2. String splitting
String splitting is to split a string into multiple strings. JavaScript provides us with a very convenient function , such as: The second parameter of
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"];
split represents the maximum length of the returned string array.
3. Get the string length
The 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 JavaScripts. 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 it is found. If it is 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 the string should not 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"
The default is to only replace If you want to replace it globally when you find it for the first time, you need to put a regular global identifier, 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 details, 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 the 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 at the corresponding position Value, such as:
var myStr = "I,love,you,Do,you,love,me"; var theChar = myStr.charCodeAt(8); //111
7. String connection
The string connection 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 one, use splice:
var myStr = "I,love,you,Do,you,love,me"; var subStr = myStr.slice(1,5);//",lov"
The second one, 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"
. The difference from the first and second methods is that 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
As you can see, the match function is called on a string and accepts a regular parameter. Let’s take a look at the second example, using the exec function:
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
It’s simple. It just changes the position of the regular expression and the string. That is, the exec function is called on the regular expression and passes the parameters of the string. For the above two methods, the matching result is to return the first successfully matched string. If the match fails, null is returned.
Let’s look at a similar method search, such as:
var myStr = "I,love,you,Do,you,love,me"; var pattern = /love/; var result = myStr.search(pattern);//2
Only return the found matching string Subscript, if the match fails, -1 is returned.
11. String comparison
Compare two strings. The comparison rule is to compare in alphabetical order, such as:
var myStr = "chicken"; var myStrTwo = "egg"; var first = myStr.localeCompare(myStrTwo); // -1 first = myStr.localeCompare("chicken"); // 0 first = myStr.localeCompare("apple"); // 1
12. Example
Finally we Let’s take a look at a front-end written test question from Qunar.com. I believe many children have done this question. Question: Write a getSuffix function to obtain the suffix name of the input parameter. For example, enter abcd.txt and return txt. Attached is my answer:
function getSuffix(file){ return file.slice(file.lastIndexOf(".") + 1,file.length); }
Conclusion
I believe there should be more than these string manipulation functions in JavaScript, but the ones listed above should all be very commonly used. If there is anything you need to add, please feel free to add it! I hope that after seeing this, you will be able to face the string written interview questions very calmly.

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
