Home Web Front-end JS Tutorial Detailed explanation of the properties and methods of the String object of JavaScript native objects_javascript skills

Detailed explanation of the properties and methods of the String object of JavaScript native objects_javascript skills

May 16, 2016 pm 04:09 PM
javascript Attributes method

length

The

length property returns the number of characters in a string.

length obtains the length based on the UTF-16 encoding of the string. The length of an empty string is 0. length cannot be modified.

charAt()

The charAt() method returns the character at the specified position. Note that JavaScript does not have a character data type distinct from the string type, so the characters returned are strings of length 1.

stringObject.charAt(index)

The parameter index is required. A number that represents a certain position in a string, that is, the subscript of a character in the string. The index of the first character in the string is 0. If the parameter index is not between 0 and string.length, this method returns an empty string.

Note: The charAt() method may have problems supporting some non-BMP (Basic-Multilingual-Plane) characters. Reference: MDN

charCodeAt()

The charCodeAt() method returns the Unicode encoding of the character at the specified position. This return value is an integer between 0 – 65535.
The method charCodeAt() performs a similar operation to the charAt() method, except that the former returns the encoding of the character at the specified position, while the latter returns a substring of characters.

stringObject.charCodeAt(index)

The parameter index is optional. A number that represents a certain position in a string, that is, the subscript of a character in the string. The index of the first character in the string is 0. If index is negative, or greater than or equal to the length of the string, charCodeAt() returns NaN. The default is 0 when index is empty.

Unicode encoding range is 0 to 1,114,111. The first 128 Unicode encodings match ASCII character encodings. The value returned by the charCodeAt() method is always less than 65536, because characters with higher values ​​appear in pairs and need to be retrieved simultaneously with charCodeAt(i) and charCodeAt(i 1).

concat() – Deprecated

The concat() method is used to concatenate two or more strings.

stringObject.concat(stringX, stringX, …, stringX)

The parameter stringX is required. Is one or more string objects that will be concatenated into a string.

The

concat() method will convert all its parameters into strings, then concatenate them to the end of the string stringObject in order, and return the concatenated string. Note that the stringObject itself is not changed.

Note that it is strongly recommended to use the " " operator to concatenate strings as an alternative to this method, which is more efficient. Reference: concat vs vs join.
indexOf()

The indexOf() method returns the position of the first occurrence of a specified string value in the string.

stringObject.indexOf(searchvalue, fromindex)

The parameter searchvalue is required and specifies the string value to be retrieved. The parameter fromindex is an optional integer parameter. Specifies the position in the string to begin searching. Its legal values ​​are 0 to stringObject.length – 1. If this parameter is omitted, the search will start from the first character of the string.

This method will retrieve the string stringObject from beginning to end to see if it contains the substring searchvalue. The starting position of the search is at the fromindex of the string or the beginning of the string (when fromindex is not specified). If a searchvalue is found, the position of the first occurrence of searchvalue is returned. Character positions in stringObject start from 0.

Note: The indexOf() method is case-sensitive! If the string value to be retrieved does not appear, the method returns -1.

lastIndexOf()

lastIndexOf() method can return the last occurrence position of a specified string value, searching from back to front at the specified position in a string.

The parameters and usage methods of lastIndexOf() and indexOf() are the same, except that they search from back to front.

Copy code The code is as follows:

var str="Hello world world!"

console.log(str.indexOf("wo")); //6
console.log(str.indexOf("wo",2)); //6
console.log(str.indexOf("wo",10)); //12
console.log(str.lastIndexOf("wo")); //12
console.log(str.lastIndexOf("wo",2)); //-1
console.log(str.lastIndexOf("wo",10)); //6

localeCompare()

Compares two strings in local specific order.

stringObject.localeCompare(target)

The parameter target is required, the string to be compared with stringObject in a local specific order.

Returns the number of the comparison result. If stringObject is less than target, localeCompare() returns a number less than 0. If stringObject is greater than target, this method returns a number greater than 0. If the two strings are equal, or there is no difference according to local collation, this method returns 0.

When the < and > operators are applied to strings, they only compare strings using the character's Unicode encoding, regardless of local collation. The order generated this way is not necessarily correct. For example, in Spanish, the character "ch" is usually ordered as a character that appears between the letters "c" and "d". The localeCompare() method provides a way to compare strings, taking into account the default local collation.

The parameters of localeCompare() in some advanced browsers also support locales and options, refer to the following code and MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript /Reference/Global_Objects/String/localeCompare

Copy code The code is as follows:

//Different cultures have different sorting rules
console.log('ä'.localeCompare('z', 'de')); //-1
console.log('ä'.localeCompare('z', 'sv')); //1

match()

The

match() method retrieves a specified value within a string, or finds a match for one or more regular expressions.

This method is similar to indexOf() and lastIndexOf(), but it returns the specified value instead of the position of the string.

stringObject.match(regexp)

The parameter regexp can be a string or a regular expression RegExp object.

Returns an array storing matching results. The contents of this array depend on whether regexp has the global flag g.

If the regexp does not have the g flag, then the match() method can only perform one match in the stringObject. If no matching text is found, match() returns null. Otherwise, it returns an array with information about the matching text it found. The 0th element of the array holds the matching text, while the remaining elements hold the text that matches the regular expression's subexpression. In addition to these regular array elements, the returned array contains two object properties. The index attribute declares the position of the starting character of the matching text in stringObject, and the input attribute declares a reference to stringObject.

If the regexp has flag g, the match() method performs a global search to find all matching substrings in the stringObject. If no matching substring is found, null is returned. If one or more matching substrings are found, an array is returned. However, the content of the array returned by global matching is very different from the former. Its array elements store all matching substrings in stringObject, and there is no index attribute or input attribute.

Without the g flag, calling stringObject.match(regexp) has the same result as calling regexp.exec(stringObject). In global search mode, match() does not provide information about the text matched by the subexpression, nor does it declare the position of each matching substring. If you need this globally retrieved information, you can use RegExp.exec().

Note: If you need to know whether a string matches a regular expression, use regexp.test(string); if you only want to match it once, use regexp.exec(string) instead of string.match(regexp).

Copy code The code is as follows:

var str="Hello world!"
var str2="1 plus 2 equal 3"

console.log(str.match("world")); //["world", index: 6, input: "Hello world!"]
console.log(str2.match(/d /g)); //["1", "2", "3"]

replace()

The

replace() method is used to replace some characters with other characters in a string, or replace a substring that matches a regular expression.

stringObject.replace(regexp/substr, replacement)

The parameters regexp/substr are required. A RegExp object that specifies the substring or pattern to be replaced. If the value is a string, it is retrieved as a literal literal pattern rather than first being converted to a RegExp object. Parameter replacement is required. is a string value. Specifies functions for replacing text or generating replacement text.

The

method returns a new string obtained by replacing the first or all matches of regexp with replacement.

The replace() method of string stringObject performs a search and replace operation. It will look for substrings in stringObject that match regexp and replace those substrings with replacement. If the regexp has the global flag g, then the replace() method replaces all matching substrings. Otherwise, it only replaces the first matching substring.

replacement can be a string or a function. If it is a string, then each match will be replaced by the string. But the $ character in replacement has a specific meaning. As shown below, it illustrates that the string obtained from the pattern match will be used for replacement:

1.$$ – $
2.$` - the text to the left of the matched substring.
3.$' - the text to the right of the matched substring.
4.$& - substring matching regexp.
5.$number - Text that matches the number-th subexpression in regexp.

replacement can be a function, in which case the function is called for each match and the string it returns will be used as the replacement text. The first parameter of this function is a string matching the pattern. The next argument is a string that matches the subexpression in the pattern, and there can be 0 or more such arguments. The next parameter is an integer that declares the position in the stringObject where the match occurs. The last parameter is the stringObject itself.

Copy code The code is as follows:

//Replace once
var str = "Hello Microsoft!";
console.log(str.replace(/Microsoft/, "Google")); //Hello Google!
console.log(str); //Hello Microsoft!

//Replace multiple times
var str2 = "Hello Microsoft! and Microsoft! and Microsoft! or Microsoft!";
console.log(str2.replace(/Microsoft/g, "Google")); //Hello Google! and Google! and Google! or Google!

//Character conversion
var str3 = "Doe, John";
console.log(str3.replace(/(w )s*, s*(w )/, "$2 $1")); //John Doe

var str4 = '"a", "b"';
console.log(str4.replace(/"([^"]*)"/g, "'$1'")); //'a', 'b'

//Use function
var str5 = 'aaa bbb ccc';
console.log(str5.replace(/bw b/g, function(word){
return word.substring(0,1).toUpperCase() word.substring(1);}
)); //Aaa Bbb Ccc

search()

The

search() method is used to retrieve a specified substring in a string, or to retrieve a substring that matches a regular expression.

stringObject.search(regexp)

The parameter regexp can be the substring that needs to be retrieved in stringObject, or it can be the RegExp object that needs to be retrieved.

Returns the starting position of the first substring in stringObject that matches regexp. If no matching substring is found, -1 is returned.

Note: The search() method does not perform a global match, it ignores the g flag. It also ignores the lastIndex property of the regexp and always retrieves from the beginning of the string, which means it always returns the first matching position of the stringObject.

Copy code The code is as follows:

var str = "Hello Microsoft!";
console.log(str.search(/Microsoft/)); //6

일치하는 문자열이 있는지만 알고 싶다면 search() 메서드를 사용하는 것은 test() 메서드를 사용하는 것과 거의 동일합니다. 더 많은 정보를 얻으려면 match() 및 exec() 메서드를 사용할 수 있지만 효율성이 낮습니다.

슬라이스()

slice() 메소드는 문자열의 특정 부분을 추출하고 추출된 부분을 새로운 문자열로 반환합니다.

stringObject.slice(시작, 끝)

start 매개변수는 추출할 세그먼트의 시작 인덱스입니다. 음수인 경우 이 매개변수는 문자열 끝부터 시작하는 위치를 지정합니다. 즉, -1은 문자열의 마지막 문자를 나타내고, -2는 마지막에서 두 번째 문자를 나타내는 식입니다.

매개변수 end는 추출할 조각의 끝 바로 뒤에 오는 인덱스입니다. 이 매개변수를 지정하지 않으면 추출할 하위 문자열에는 원래 문자열의 처음부터 끝까지의 문자열이 포함됩니다. 이 매개변수가 음수이면 문자열 끝에서부터의 위치를 ​​지정합니다.

메서드는 새 문자열을 반환합니다. 시작(포함)부터 끝(제외)까지 stringObject 문자열의 모든 문자를 포함합니다.

참고: String 개체의 Slice(), substring() 및 substr() 메서드는 모두 문자열의 지정된 부분을 반환할 수 있습니다. 모든 상황에서 Slice() 메서드를 사용하는 것이 좋습니다.

코드 복사 코드는 다음과 같습니다.

var str = "안녕하세요 마이크로소프트!";
console.log(str.slice(6)); //마이크로소프트!
console.log(str.slice(6, 12)); //마이크로

하위 문자열()

지원 중단되었으므로 대신 Slice()를 사용하는 것이 좋습니다.

substr()

지원 중단되었으므로 대신 Slice()를 사용하는 것이 좋습니다.

toLocaleLowerCase()

권장되지 않습니다. 터키어와 같은 일부 언어에서만 유용합니다. 대신 toLowerCase()를 사용하는 것이 좋습니다.

toLocaleUpperCase()

권장되지 않습니다. 터키어와 같은 일부 언어에서만 유용합니다. 대신 toUpperCase()를 사용하는 것이 좋습니다.

toLowerCase()

toLowerCase() 메서드는 문자열을 소문자로 변환하는 데 사용됩니다.

toUpperCase()

toUpperCase() 메서드는 문자열을 대문자로 변환하는 데 사용됩니다.

문자열 객체에는 HTML 태그에 대한 다양한 메서드도 있습니다: 앵커(), big(), 깜박임(), 볼드(), 고정(), 글꼴 색상(), 글꼴 크기(), 기울임꼴(), 링크(), 작은 (), 파업(), 하위(), sup(). 그들은 주로 String 객체에 대해 HTML 형식을 수행합니다. 요즘에는 이를 적용하는 사람이 거의 없으며 사용을 권장하지 않습니다.

방법 시연 예:

코드 복사 코드는 다음과 같습니다.


Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to delete WeChat friends? How to delete WeChat friends How to delete WeChat friends? How to delete WeChat friends Mar 04, 2024 am 11:10 AM

WeChat is one of the mainstream chat tools. We can meet new friends, contact old friends and maintain the friendship between friends through WeChat. Just as there is no such thing as a banquet that never ends, disagreements will inevitably occur when people get along with each other. When a person extremely affects your mood, or you find that your views are inconsistent when you get along, and you can no longer communicate, then we may need to delete WeChat friends. How to delete WeChat friends? The first step to delete WeChat friends: tap [Address Book] on the main WeChat interface; the second step: click on the friend you want to delete and enter [Details]; the third step: click [...] in the upper right corner; Step 4: Click [Delete] below; Step 5: After understanding the page prompts, click [Delete Contact]; Warm

How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. Mar 28, 2024 pm 12:50 PM

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) May 01, 2024 pm 12:01 PM

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

How to enter bios on Colorful motherboard? Teach you two methods How to enter bios on Colorful motherboard? Teach you two methods Mar 13, 2024 pm 06:01 PM

Colorful motherboards enjoy high popularity and market share in the Chinese domestic market, but some users of Colorful motherboards still don’t know how to enter the bios for settings? In response to this situation, the editor has specially brought you two methods to enter the colorful motherboard bios. Come and try it! Method 1: Use the U disk startup shortcut key to directly enter the U disk installation system. The shortcut key for the Colorful motherboard to start the U disk with one click is ESC or F11. First, use Black Shark Installation Master to create a Black Shark U disk boot disk, and then turn on the computer. When you see the startup screen, continuously press the ESC or F11 key on the keyboard to enter a window for sequential selection of startup items. Move the cursor to the place where "USB" is displayed, and then

The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) May 04, 2024 pm 06:01 PM

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

How to set font size on mobile phone (easily adjust font size on mobile phone) How to set font size on mobile phone (easily adjust font size on mobile phone) May 07, 2024 pm 03:34 PM

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

Summary of methods to obtain administrator rights in Win11 Summary of methods to obtain administrator rights in Win11 Mar 09, 2024 am 08:45 AM

A summary of how to obtain Win11 administrator rights. In the Windows 11 operating system, administrator rights are one of the very important permissions that allow users to perform various operations on the system. Sometimes, we may need to obtain administrator rights to complete some operations, such as installing software, modifying system settings, etc. The following summarizes some methods for obtaining Win11 administrator rights, I hope it can help you. 1. Use shortcut keys. In Windows 11 system, you can quickly open the command prompt through shortcut keys.

Detailed explanation of Oracle version query method Detailed explanation of Oracle version query method Mar 07, 2024 pm 09:21 PM

Detailed explanation of Oracle version query method Oracle is one of the most popular relational database management systems in the world. It provides rich functions and powerful performance and is widely used in enterprises. In the process of database management and development, it is very important to understand the version of the Oracle database. This article will introduce in detail how to query the version information of the Oracle database and give specific code examples. Query the database version of the SQL statement in the Oracle database by executing a simple SQL statement

See all articles