SoFunction
Updated on 2025-02-28

Detailed discussion of String objects in Javascript

The Sting String object is one of the built-in objects provided by Javascript.

Pay special attention here that the first character in the string is the 0th bit, and the second is the 1st bit.

1. Method to create a string object

[var] String object instance name = new String(string)

Or var String object instance name = string value

example:

var str = "Hello World";

var str1 = new String("This is a string");

Properties of

length: Returns the length of the string

var intlength = //intlength = 11

Method

charAt(*): Returns a single character in the *th position of the string

var x = "abcdefg"; var y = (3); //y="d"

charCodeAt(*): Returns the ASCII code of a single character in the string position at *

No details
Copy the codeThe code is as follows:

fromCharCode(): Accepts a specified Unicode value and returns a string.

((72,69,76,76,79)); //The output result is HELLO

indexOf(): Find another string object from the string, find the return position successfully, otherwise return -1

("children".indexOf("l",0)); //The output result is 3

("children".indexOf("l",1)); //The output result is 3

("children".indexOf("l",4)); //The output result is -1

lastIndexOf(): Similar to indexOf() method, the difference is that the search direction is opposite, search from behind to front

("children".lastIndexOf("l",4)); //The output result is 3

split(delimiter character): Returns an array, the array is separated from the string, and the delimiter character determines the separation.

'l&o&v&e'.split('&'); //Return the array l,o,v,e

substring(): equivalent to string cropping function

substring(<start>[,<end>])

("children".substring(1,3)); //The output result is hil

substr(): It is also equivalent to cropping, pay attention to the difference from substring()

substr(<start>[,<length>])
Copy the codeThe code is as follows:

("children".substr(1,3)); //The output result is hil. Here we should pay attention to comparison with substing. Although the results are the same, the algorithm and ideas are different.

toLowerCase() and toUpperCase(): function similarly, but return a string with the same original string. The only difference is that all letters in the former are lowercase and the latter are uppercase.

("LOVE".toLowerCase()); //The output result is love

("love".toUpperCase()); //The output result is LOVE