小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
路难行,行路难,一身汗水,满心长。脚下百里路,头顶艳阳天。坚定如磐石,信念似火烧。好男儿,人穷志不缺,天道也酬勤。四方走,走四方,一身是胆,豪气壮。前方坎坷途,千难万般阻。心若有明灯,身似般若行。好男儿,大志存高远,四海皆为家。
判断是否包含
includes() 方法
includes() 方法用于判断一个字符串是否包含在另一个字符串中,返回布尔值。
str.includes(searchString[, position])
- searchString :在 str 字符串中搜索的字符串。
- position :可选项。从当前字符串的哪个索引位置开始搜寻子字符串,默认值为0。
值得注意的是,includes() 方法是区分大小写的。
var str = 'To be, or not to be,that is the question.';
console.log(str.includes("To be")); // true
console.log(str.includes('question'));//true
console.log(str.includes("nonexistent"));// false
console.log(str.includes( 'To be', 1)); // false
console.log(str.includes("TO BE")); // false
startsWith() 方法
startsWidth() 方法用于判断当前字符串是否是以另外一个给定的子字符串“开头”的,返回布尔值。
str.startsWith(searchStringl[, position])
- searchString :在 str 字符串中搜索的字符串。
- position :可选项。从当前字符串的哪个索引位置开始搜寻子字符串,默认值为0.
值得注意的是,startsWidth() 方法是区分大小写的。
var str = "To be, or not to be, that is the question.";
console.log(str.startsWith("To be"); // true
console.log(str.startsWith("not to be")); // false
console.log(str.startsWith("not to be",10));// true
endsWith() 方法
endsWith() 方法用于判断当前字符串是否是以另外一个给定的子字符串“结尾”的,返回布尔值。
str.endsWith(searchString[, position])
- searchString :在 str 字符串中搜索的字符串。
- position :可选项。从当前字符串的哪个索引位置开始搜寻子字符串,默认值为0。
注意的是,endsWith() 方法是区分大小写.
var str="To be, or not to be, that is the question.";
console.log( str.endsWith("question."));// true
console.log( str.endsWith("to be")); // false
console.log( str.endsWith("to be", 19)); // true
repeat() 方法
repeat()方法用于将原字符串重复n次,返回一个新字符串。
str.repeat(number)
- number :表示将元字符串重复的次数。
console.log("x'.repeat(3);//"xxx"
console.log("hello" .repeat(2));// "hellohello”
console.log("na".repeat(O));://""
number参数具有以下几种情况:
- 如果number参数为小数的话,则会向下取整。
- 如果number参数为负数或者无穷大的话,则会报错。
- 如果number参数为 NaN 的话,则为0。
- 如果number 参数为字符串,则会先转换为数字值。
模板字符串是什么
模板字符串 (Template String) 是增强版的字符串,使用反引号(``)来代替镑通字符串中的用双引号和单引号。它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量。
//普通字符串
console.log( `In JavaScript '\n' is a line-feed.` );
//多行字符串
console.log( `string text line 1
string text line 2`);
//字符串中嵌入变量
let name = "Bob", time = "today";
console.log(`Hello ${name}, how are you ${time}? `);
带标签的模板字符串
模板字符串的功能可以紧跟在一个函数名后面,该函数将被调用来处理这个模板字符串。这被称为“标签模板”功能( Tagged Template ) 。
console.log('abc');
console.log`abc`;
标签模板其实不是模板,而是函数调用的一种特殊形式。“标签”指的就是函数,紧跟在后面的模板字符串就是它的参数。
原始字符串
在标签函数的第一个参数中,存在一个特殊的属性raw ,可以通过它来访问模板字符串的原始字符串,而不经过特殊字符的替换。
function tag(strings) {
console.log(strings.raw[0]);
}
tag`string text line 1 ln string text line 2`;
另外,使用Stringraw()方法创建原始字符串和使用默认模板函数和字符串连接创建是一样的。
var str = String.raw`Hi\n${2+3}`;//"Hi\n5!"
console.log(str.length);//6
console.log(str.split("").join("."));//"Hi\n,5,!"