当前位置:网站首页>String string
String string
2022-07-28 23:28:00 【Corner sheep】
List of articles
- String
- You can also use String Function to generate or convert other values into strings :
- Template literal
- Character access
- character string .raw()
- String length
- String.prototype.at()
- String.prototype.charAt()
- String.prototype.concat()
- String.prototype.localeCompare()
- String.prototype.match()
- RegExp.prototype.exec() And /g
- String.prototype.padStart()
- String.prototype.repeat()
- String.prototype.replace()
- String.prototype.replaceAll()
- String.prototype.search()
- String.prototype.slice()
- String.prototype.split()
- String.prototype.startsWith()
- String.prototype.substring()
String
String A global object is a constructor for a string or a sequence of characters .
You can also use String Function to generate or convert other values into strings :
String(thing);
new String(thing);
Template literal
from ECMAScript 2015 Start , String literals can also be called template literals :
`hello world` `hello! world!` `hello ${
who}` escape `<a>${
who}</a>`
Character access
// There are two ways to access a single character in a string . First of all charAt() Method :
return "cat".charAt(1); // returns "a"
// Copy to clipboard
// Another way ( stay ECMAScript 5 Introduction in ) Is to treat a string as an array like object , Where a single character corresponds to a numeric index :
return "cat"[1]; // returns "a"
character string .raw()
static state String.raw() The method is the markup function of the template text . This is similar to rPython Prefix in , or @ C# Prefix of string text in . It is used to get the original string form of the template text , That is, processing replacement ( for example ${foo}), But do not handle escape ( for example \n).
// Create a variable that uses a Windows
// path without escaping the backslashes:
const filePath = String.raw`C:\Development\profile\aboutme.html`;
console.log(`The file was uploaded from: ${
filePath}`);
// expected output: "The file was uploaded from: C:\Development\profile\aboutme.html"
String length
Object's length attribute String Contains the length of the string , With UTF-16 Code units represent .length Is a read-only data attribute of a string instance .
const str = "Life, the universe and everything. Answer:";
console.log(`${
str} ${
str.length}`);
// expected output: "Life, the universe and everything. Answer: 42"
String.prototype.at()
The at() Method accepts an integer value and returns a String By a single... At the specified offset UTF-16 New values composed of code units . This method allows positive and negative integers . Negative integers count down from the last string character .
const sentence = "The quick brown fox jumps over the lazy dog.";
let index = 5;
console.log(
`Using an index of ${
index} the character returned is ${
sentence.at(index)}`
);
// expected output: "Using an index of 5 the character returned is u"
index = -4;
console.log(
`Using an index of ${
index} the character returned is ${
sentence.at(index)}`
);
// expected output: "Using an index of -4 the character returned is d"
String.prototype.charAt()
The String Object's charAt() Method returns a new string , The string consists of a single... Located in the string at the specified offset UTF-16 Code unit composition .
const sentence = "The quick brown fox jumps over the lazy dog.";
const index = 4;
console.log(`The character at index ${
index} is ${
sentence.charAt(index)}`);
// expected output: "The character at index 4 is q"
String.prototype.concat()
The concat() Method connects a string parameter to the call string and returns a new string .
const str1 = "Hello";
const str2 = "World";
console.log(str1.concat(" ", str2));
// expected output: "Hello World"
console.log(str2.concat(", ", str1));
// expected output: "World, Hello"
##### String.prototype.includes()
The includes() Method to perform a case sensitive search , To determine whether a string can be found in another string , return true or false Discretion .
const sentence = "The quick brown fox jumps over the lazy dog.";
const word = "fox";
console.log(
`The word "${
word}" ${
sentence.includes(word) ? "is" : "is not" } in the sentence`
);
// expected output: "The word "fox" is in the sentence"
##### String.prototype.endsWith()
The endsWith() Method to determine whether the string ends with the character of the specified string , return true or false Discretion .
const str1 = "Cats are the best!";
console.log(str1.endsWith("best", 17));
// expected output: true
const str2 = "Is this a question";
console.log(str2.endsWith("?"));
// expected output: false
##### String.prototype.indexOf()
The indexOf() Method gives a parameter : Substring to search , Search the entire call string , And returns the index of the first occurrence of the specified substring . Given the second parameter : A number , This method returns the first occurrence of the specified substring at the index greater than or equal to the specified number .
const paragraph =
"The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?";
const searchTerm = "dog";
const indexOfFirst = paragraph.indexOf(searchTerm);
console.log(
`The index of the first "${
searchTerm}" from the beginning is ${
indexOfFirst}`
);
// expected output: "The index of the first "dog" from the beginning is 40"
console.log(
`The index of the 2nd "${
searchTerm}" is ${
paragraph.indexOf( searchTerm, indexOfFirst + 1 )}`
);
// expected output: "The index of the 2nd "dog" is 52"
##### String.prototype.lastIndexOf()
The lastIndexOf() Method gives a parameter : Substring to search , Search the entire call string , And returns the index of the last occurrence of the specified substring . Given the second parameter : A number , This method returns the last occurrence of the specified substring at the index less than or equal to the specified number .
const paragraph =
"The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?";
const searchTerm = "dog";
console.log(
`The index of the first "${
searchTerm}" from the end is ${
paragraph.lastIndexOf( searchTerm )}`
);
// expected output: "The index of the first "dog" from the end is 52"
String.prototype.localeCompare()
The localeCompare() Method returns a number , Indicates that the reference string is before the sort order 、 Then it is the same as the given string .
const a = "réservé"; // with accents, lowercase
const b = "RESERVE"; // no accents, uppercase
console.log(a.localeCompare(b));
// expected output: 1
console.log(a.localeCompare(b, "en", {
sensitivity: "base" }));
// expected output: 0
String.prototype.match()
The match() Method retrieval will The result of string matching with regular expression .
const paragraph = "The quick brown fox jumps over the lazy dog. It barked.";
const regex = /[A-Z]/g;
const found = paragraph.match(regex);
console.log(found);
// expected output: Array ["T", "I"]
RegExp.prototype.exec() And /g
If the regular expression has /g sign , So many calls .exec() You will get all matching results . If there is no matching result ,.exec() It will return null. Before that, each matching object will be returned . This object contains the captured substring and more information .
for instance : Get all strings between double quotes
String.prototype.padStart()
The padStart() Method to fill the current string with another string ( if necessary , Many times ), Until the result string reaches the given length . Apply padding from the beginning of the current string .
const str1 = "5";
console.log(str1.padStart(2, "0"));
// expected output: "05"
const fullNumber = "2034399002125581";
const last4Digits = fullNumber.slice(-4);
const maskedNumber = last4Digits.padStart(fullNumber.length, "*");
console.log(maskedNumber);
// expected output: "************5581"
String.prototype.repeat()
The repeat() Method constructs and returns a new string , The string contains a specified number of copies of the string that calls it , And connected together .
const chorus = "Because I'm happy. ";
console.log(`Chorus lyrics for "Happy": ${
chorus.repeat(2)}`);
// 'Chorus lyrics for "Happy": Because I'm happy. Because I'm happy. '
String.prototype.replace()
The replace() Method returns a new string , among a Some or all of the match is apattern Replace replacement.Thepattern It can be a string or a RegExp, also replacement It can be the string or function called by each match . If pattern Is a string , Only the first match will be replaced .
The original string remains unchanged .
const p =
"The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?";
console.log(p.replace("dog", "monkey"));
// expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"
const regex = /Dog/i;
console.log(p.replace(regex, "ferret"));
// expected output: "The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?"
String.prototype.replaceAll()
The replaceAll() Method returns a new string , All of them match a all pattern Replace with a replacement.Thepattern It can be a string or a RegExp, also replacement It can be the string or function called by each match .
The original string remains unchanged .
const p =
"The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?";
console.log(p.replaceAll("dog", "monkey"));
// expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"
// global flag required when calling replaceAll with regex
const regex = /Dog/gi;
console.log(p.replaceAll(regex, "ferret"));
// expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"
String.prototype.search()
The search() Method to search regular expressions and this String Match between objects .
const paragraph =
"The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?";
// any character that is not a word character or whitespace
const regex = /[^\w\s]/g;
console.log(paragraph.search(regex));
// expected output: 43
console.log(paragraph[paragraph.search(regex)]);
// expected output: "."
String.prototype.slice()
The slice() Method extracts part of a string and returns it as a new string , Without modifying the original string .
const str = "The quick brown fox jumps over the lazy dog.";
console.log(str.slice(31));
// expected output: "the lazy dog."
console.log(str.slice(4, 19));
// expected output: "quick brown fox"
console.log(str.slice(-4));
// expected output: "dog."
console.log(str.slice(-9, -5));
// expected output: "lazy"
String.prototype.split()
The split() Methods will a Divide String Is an ordered list of substrings , Put these substrings into an array , And return the array . Division is accomplished through search patterns ; The pattern is provided as the first parameter in the method call .
const str = "The quick brown fox jumps over the lazy dog.";
const words = str.split(" ");
console.log(words);
// expected output: "fox"
const chars = str.split("");
console.log(chars[8]);
// expected output: "k"
const strCopy = str.split();
console.log(strCopy);
// expected output: Array ["The quick brown fox jumps over the lazy dog."]
String.prototype.startsWith()
The startsWith() Method to determine whether the string starts with the character of the specified string , return true or false Discretion .
const str1 = "Saturday night plans";
console.log(str1.startsWith("Sat"));
// expected output: true
console.log(str1.startsWith("Sat", 3));
// expected output: false
String.prototype.substring()
The substring() Method returns string The part between the beginning and end of the index , Or return to the end of the string .
const str = "Mozilla";
console.log(str.substring(1, 3));
// expected output: "oz"
console.log(str.substring(2));
// expected output: "zilla"
边栏推荐
- Hands on Teaching of servlet use (1)
- Performance optimized APK slimming
- [image segmentation] vein segmentation based on directional valley detection with matlab code
- 《MySQL数据库进阶实战》读后感(SQL 小虚竹)
- Applet, JS, transfer object jump transfer parameter problem
- Recurrent neural network (RNN)
- Nacos配置热更新的4种方式、读取项目配置文件的多种方式,@value,@RefreshScope,@NacosConfigurationProperties
- The US FCC provided us $1.6 billion to support domestic operators to remove Huawei and ZTE equipment
- 【图像分割】基于方向谷形检测实现静脉纹路分割附MATLAB代码
- The applet vant webapp component is missing, and the referenced component reports an error
猜你喜欢

【MySQL系列】 MySQL表的增删改查(进阶)

Retrofit Usage Summary

如何在VR全景中嵌入AI数字人功能?打造云端体验感

参加竞赛同学们的留言 : 第十七届的记忆

What if win11 quick copy and paste cannot be used? Win11 shortcut copy and paste cannot be used

How strong is this glue?

Basic concept of MySQL database and deployment of MySQL version 8.0 (I)

There are four ways for Nacos to configure hot updates and multiple ways to read project configuration files, @value, @refreshscope, @nacosconfigurationproperties

A new MPLS note from quigo, which must be read when taking the IE exam ---- quigo of Shangwen network

Applet Download Preview PDF, document cannot open solution
随机推荐
欲要让数字零售继续发挥作用,我们需要对数字零售赋予新的内涵和意义
通过Wi-Fi 7实现极高吞吐量——洞察下一代Wi-Fi物理层
pg_ Installation and use of RMAN "PostgreSQL"
[filter tracking] target tracking based on EKF, TDOA and frequency difference positioning with matlab code
【MongoDB】MongoDB数据库的基础使用,特殊情况以及Mongoose的安装和创建流程(含有Mongoose固定版本安装)
【滤波跟踪】基于EKF、时差和频差定位实现目标跟踪附matlab代码
MySQL常用的日期时间函数
Failure [INSTALL_FAILED_TEST_ONLY: installPackageLI]
华为无线设备配置利用WDS技术部署WLAN业务
6 个超级良心的开源教程!
Istio微服务治理网格的全方面可视化监控(微服务架构展示、资源监控、流量监控、链路监控)
Advanced C language: pointer (3)
以流量为主导的数字零售的发展模式,仅仅只是一个开始
In 2020, the top ten domestic IC design enterprises will be exposed! These five industrial challenges still need to be overcome!
当初的“你“为什么做测试/开发程序员?自己存在的价值......
Thesis reading (2) - vggnet of classification
The US FCC provided us $1.6 billion to support domestic operators to remove Huawei and ZTE equipment
Programmer growth Chapter 30: artifact of identifying true and false needs
It's settled! All products of Nezha s will be launched on July 31
The applet vant webapp component is missing, and the referenced component reports an error