Home  >  Article  >  Web Front-end  >  How to replace the first character of a string with other characters in es6

How to replace the first character of a string with other characters in es6

青灯夜游
青灯夜游Original
2022-05-19 15:04:203253browse

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")".

How to replace the first character of a string with other characters in es6

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);

How to replace the first character of a string with other characters in es6

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")

How to replace the first character of a string with other characters in es6

[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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn