扫码一下
查看教程更方便
以下是方法及其描述的列表。
序号 | 方法 | 描述 |
---|---|---|
1 | string.prototype.startswith(searchstring, position = 0) | 如果接收者以 searchstring 开头,则返回 true; 该位置允许您指定要检查的字符串的起始位置。 |
2 | string.prototype.endswith(searchstring, endposition = searchstring.length) | 如果接收者以 searchstring 开头,则返回 true; 该位置允许您指定要检查的字符串的起始位置。 |
3 | string.prototype.includes(searchstring, position = 0) | 如果接收者包含 searchstring,则返回 true; position 允许您指定要搜索的字符串的起始位置。 |
4 | string.prototype.repeat(count) | 返回接收者,连接计数次。 |
模板文字是允许嵌入表达式的字符串文字。 模板字符串使用反引号 (``) 而不是单引号或双引号。 因此,模板字符串可以写成
var greeting = `hello world!`;
模板字符串可以使用占位符来使用 ${ }
语法进行字符串替换,如下所示。
var name = "brendan";
console.log('hello, ${name}!');
成功执行上述代码后会显示以下输出。
hello, brendan!
var a = 10;
var b = 10;
console.log(`the sum of ${a} and ${b} is ${a b} `);
成功执行上述代码后会显示以下输出。
the sum of 10 and 10 is 20
function fn() { return "hello world"; }
console.log(`message: ${fn()} !!`);
成功执行上述代码后会显示以下输出。
message: hello world !!
模板字符串可以包含多行。
var multiline = `
this is
a string
with multiple
lines`;
console.log(multiline)
成功执行上述代码后会显示以下输出。
this is
a string
with multiple
line
es6 包含用于原始字符串的标记函数 string.raw
,其中反斜杠没有特殊含义。 string.raw
使我们能够像在正则表达式文字中那样编写反斜杠。 考虑以下示例。
var text =`hello \n world`
console.log(text)
var raw_text = string.raw`hello \n world `
console.log(raw_text)
成功执行上述代码后会显示以下输出。
hello
world
hello \n world
标签是可以解释和处理模板文字的函数。 标签出现在模板文字的前面。 语法如下所示。
let output_fromtag = tagfunction `template literal with ${variable1} , ${variable2}`
标记函数实现语法如下
function tagfunction(literals,...variable_values){
//process
return "some result"
}
以下示例定义了一个标记函数 mytagfn()
。 它显示传递给它的参数。 显示后,它将完成返回给调用者。
function mytagfn(literals,...values){
console.log("literal values are");
for(let c of literals){
console.log(c)
}
console.log("variable values are ");
for(let c of values){
console.log(c)
}
return "done"
}
let company = `jiyik`
let company_location = `mumbai`
let result = mytagfn `hello this is ${company} from ${company_location}`
console.log(result)
上述代码的输出将如下所述
//literal
literal values are
hello this is
from
//values
variable values are
jiyik
mumbai
done
下面的标记函数采用模板文字并将其转换为大写,如下所示
function converttouppertagfn(literals, ...values) {
let result = "";
for (let i = 0; i < literals.length; i ) {
result = literals[i];
if (i < values.length) {
result = values[i];
}
}
return result.touppercase();
}
let company = `jiyik`
let company_location = `mumbai`
let result = converttouppertagfn `hello this is ${company} from ${company_location}`
console.log(result)
上述代码的输出将如下所述
hello this is jiyik from mumbai
静态 string.fromcodepoint()
方法返回使用指定的 unicode 代码点序列创建的字符串。 如果传递了无效的代码点,该函数将抛出 rangeerror
。
console.log(string.fromcodepoint(42))
console.log(string.fromcodepoint(65, 90))
成功执行上述代码后会显示以下输出。
*
az