JavaScript String object

Define the String object

The JavaScript String object is used to process text strings. The syntax for creating a String object is as follows:

Among the above three methods, only the first one uses the String constructor to strictly define a string object and returns an object. The second is to call the String function to convert the parameter str to the original string string and return it. The third method is to define a string variable, but it is still treated as a string object in JavaScript.

Run the following statements to know the difference:

alert( typeof str_object ); // Output object
alert( typeof str1 ); // Output string
alert ( typeof str2 ); // Output string

##String Object attribute


##Attribute

Description


constructor A reference to the function that created the object

length The length of the string

prototype Adding properties and methods to the object


String (String) uses the length attribute length to calculate the length of the string:

    php中文网(php.cn) 

String uses indexOf() to locate a specific point in the string The position where the character first appears:

    php中文网(php.cn) 

Click the button to locate where "locate" first occurs.

0

match() function is used to find a specific character in a string, and if found, returns this character.

    php中文网(php.cn) 

replace() method replaces certain characters with other characters in a string.

    php中文网(php.cn) 

请访问 Microsoft!

String case conversion uses the function toUpperCase() / toLowerCase():

var txt="Hello World!"; // String

var txt1=txt .toUpperCase(); // txt1 text will be converted to uppercasevar txt2=txt.toLowerCase(); // txt2 text will be converted to lowercase

Strings use strong>split() Convert the function to an array:

    php中文网(php.cn) 

Special characters

In Javascript, you can use backslash (\) to insert special symbols, such as apostrophes, quotation marks and other special symbols.

View the following JavaScript code:

var txt="We are the so-called "Vikings" from the north.";

document.write(txt);

In JavaScript, single or double quotes are used to start and stop strings. This means that the above string will be cut into: We are the so-called

To solve the above problem, you can use backslashes to escape the quotes:

var txt ="We are the so-called \"Vikings\" from the north.";
document.write(txt);

JavaScript will output the correct text string: We are the so-called "Vikings" from the north.

The following table lists other special characters. You can use backslashes to escape special characters:

CodeOutput

\' Single quotation mark

\" Double quotation mark

\\ Slash bar

\n Line feed

\r Carriage return

\t tab

\b Space

\f Page change


Continuing Learning
||
php中文网(php.cn)
submit Reset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!