length
Thelength 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.
Theconcat() 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.
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
match()
Thematch() 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).
console.log(str.match("world")); //["world", index: 6, input: "Hello world!"]
console.log(str2.match(/d /g)); //["1", "2", "3"]
replace()
Thereplace() 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.
Themethod 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.
//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()
Thesearch() 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.
일치하는 문자열이 있는지만 알고 싶다면 search() 메서드를 사용하는 것은 test() 메서드를 사용하는 것과 거의 동일합니다. 더 많은 정보를 얻으려면 match() 및 exec() 메서드를 사용할 수 있지만 효율성이 낮습니다.
슬라이스()
slice() 메소드는 문자열의 특정 부분을 추출하고 추출된 부분을 새로운 문자열로 반환합니다.
stringObject.slice(시작, 끝)
start 매개변수는 추출할 세그먼트의 시작 인덱스입니다. 음수인 경우 이 매개변수는 문자열 끝부터 시작하는 위치를 지정합니다. 즉, -1은 문자열의 마지막 문자를 나타내고, -2는 마지막에서 두 번째 문자를 나타내는 식입니다.
매개변수 end는 추출할 조각의 끝 바로 뒤에 오는 인덱스입니다. 이 매개변수를 지정하지 않으면 추출할 하위 문자열에는 원래 문자열의 처음부터 끝까지의 문자열이 포함됩니다. 이 매개변수가 음수이면 문자열 끝에서부터의 위치를 지정합니다.
메서드는 새 문자열을 반환합니다. 시작(포함)부터 끝(제외)까지 stringObject 문자열의 모든 문자를 포함합니다.
참고: String 개체의 Slice(), substring() 및 substr() 메서드는 모두 문자열의 지정된 부분을 반환할 수 있습니다. 모든 상황에서 Slice() 메서드를 사용하는 것이 좋습니다.
하위 문자열()
지원 중단되었으므로 대신 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() "
")소형: " txt.small() "
")document.write("
Bold: " txt.bold() "
")기울임꼴: " txt.italics() "
")document.write("
Blink: " txt.blink() " (IE에서는 작동하지 않음)
")고정됨: " txt.fixed() "
")공격: " txt.strike() "
")document.write("
Fontcolor: " txt.fontcolor("Red") "
")글꼴 크기: " txt.fontsize(16) "
")document.write("
소문자: " txt.toLowerCase() "
")대문자: " txt.toUpperCase() "
")document.write("
하위 첨자: " txt.sub() "
")위 첨자: " txt.sup() "
")document.write("
링크: " txt.link("http://www.w3school.com.cn") "
")