Home > Article > Web Front-end > How to replace the first character of a string with other characters in es6
Replacement method: 1. Use charAt() to obtain and return the first character in the string, the syntax is "string object.charAt(0)"; 2. Use replace() to obtain the first character in the string. Characters are replaced with other characters using the syntax "String object.replace(first character value, "new character")".
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
es6 Method to replace the first character of a string with other characters
1. Use charAt() to get the string The first character in
charAt() method returns the character at the specified position. Syntax:
stringObject.charAt(index)
index 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.
var str="t679njh!mkh"; var zf=str.charAt(0); console.log(str); console.log(zf);
2. Use replace() to replace the first character obtained
replace() Method is used to replace some characters with other characters in a string, or replace a substring that matches a regular expression.
str.replace(zf,"CBA")
[Related recommendations: javascript video tutorial, web front-end】
The above is the detailed content of How to replace the first character of a string with other characters in es6. For more information, please follow other related articles on the PHP Chinese website!