search
HomeWeb Front-endJS TutorialDetailed explanation of the properties and methods of the String object of JavaScript native objects_javascript skills

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 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 형식을 수행합니다. 요즘에는 이를 적용하는 사람이 거의 없으며 사용을 권장하지 않습니다.

방법 시연 예:

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


var txt="Hello World!"

document.write("

Big: " txt.big() "

")
document.write("

소형: " txt.small() "

")

document.write("

Bold: " txt.bold() "

")
document.write("

기울임꼴: " txt.italics() "

")

document.write("

Blink: " txt.blink() " (IE에서는 작동하지 않음)

")
document.write("

고정됨: " txt.fixed() "

")
document.write("

공격: " txt.strike() "

")

document.write("

Fontcolor: " txt.fontcolor("Red") "

")
document.write("

글꼴 크기: " txt.fontsize(16) "

")

document.write("

소문자: " txt.toLowerCase() "

")
document.write("

대문자: " txt.toUpperCase() "

")

document.write("

하위 첨자: " txt.sub() "

")
document.write("

위 첨자: " txt.sup() "

")

document.write("

링크: " txt.link("http://www.w3school.com.cn") "

")


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

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 vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

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.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

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 in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

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.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

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 the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

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 vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

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.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.