📅  最后修改于: 2020-10-23 14:37:43             🧑  作者: Mango
JavaScript字符串是一个代表字符序列的对象。
有两种在JavaScript中创建字符串的方法
字符串字面量使用双引号创建。使用字符串字面量创建字符串的语法如下:
var stringname="string value";
让我们看一下创建字符串字面量的简单示例。
输出:
This is string literal
使用new关键字创建字符串对象的语法如下:
var stringname=new String("string literal");
在这里,new关键字用于创建字符串的实例。
让我们看一下用new关键字在JavaScript中创建字符串的示例。
输出:
hello javascript string
让我们用示例查看JavaScript字符串方法的列表。
Methods | Description |
---|---|
charAt() | It provides the char value present at the specified index. |
charCodeAt() | It provides the Unicode value of a character present at the specified index. |
concat() | It provides a combination of two or more strings. |
indexOf() | It provides the position of a char value present in the given string. |
lastIndexOf() | It provides the position of a char value present in the given string by searching a character from the last position. |
search() | It searches a specified regular expression in a given string and returns its position if a match occurs. |
match() | It searches a specified regular expression in a given string and returns that regular expression if a match occurs. |
replace() | It replaces a given string with the specified replacement. |
substr() | It is used to fetch the part of the given string on the basis of the specified starting position and length. |
substring() | It is used to fetch the part of the given string on the basis of the specified index. |
slice() | It is used to fetch the part of the given string. It allows us to assign positive as well negative index. |
toLowerCase() | It converts the given string into lowercase letter. |
toLocaleLowerCase() | It converts the given string into lowercase letter on the basis of host?s current locale. |
toUpperCase() | It converts the given string into uppercase letter. |
toLocaleUpperCase() | It converts the given string into uppercase letter on the basis of host?s current locale. |
toString() | It provides a string representing the particular object. |
valueOf() | It provides the primitive value of string object. |
split() | It splits a string into substring array, then returns that newly created array. |
trim() | It trims the white space from the left and right side of the string. |
JavaScript String charAt()方法返回给定索引处的字符。
输出:
v
JavaScript String concat(str)方法连接或连接两个字符串。
输出:
javascript concat example
JavaScript String indexOf(str)方法返回给定字符串的索引位置。
输出:
11
JavaScript String lastIndexOf(str)方法返回给定字符串的最后一个索引位置。
输出:
16
JavaScript String toLowerCase()方法以小写字母返回给定的字符串。
输出:
javascript tolowercase example
JavaScript String toUpperCase()方法以大写字母返回给定的字符串。
输出:
JAVASCRIPT TOUPPERCASE EXAMPLE
JavaScript字符串slice(beginIndex,endIndex)方法返回从给定的beginIndex到endIndex的字符串部分。在slice()方法中,beginIndex是包含的,endIndex是排除的。
输出:
cde
JavaScript String trim()方法从字符串删除前导和尾随空格。
输出:
javascript trim