0
点赞
收藏
分享

微信扫一扫

JavaScript 学习-11.字符串 String 对象

前言

JavaScript 中定义字符串可以用单引号或双引号,用于存储一系列字符。

字符串

声明一个变量的值是字符串类型,可以用单引号和双引号

var x ='hello world';  // 单引号
var y = "hello world"; // 双引号

如果字符串中有引号,可以用单双交替的方式

var a = "He is called 'yoyo'";  // 外双内单
var b = 'He is called "yoyo"'; // 外单内双

如果一个字符串中同时有单引号和双引号,那么此时可以用转义字符

var c = 'hello \"world\", \'yoyo\'';

当我们需要输出带转义字符的字符串:​​hello:\"yoyo​​​,那么使用转义​​\\​

下表中列举了在字符串中可以使用转义字符转义的特殊字符:

代码

输出

'

单引号

----

--------

"

双引号

\

反斜杠

\n

换行

\r

回车

\t

tab(制表符)

\b

退格符

\f

换页符

多行字符串

方法一

当我们需要定义多行字符串的时候,可以使用最笨的办法,用​​+​​号拼接字符串

var aa = '<div>\n' +
'<h1>hello world!</h1>\n' +
'</div>';
console.log(aa);

JavaScript 学习-11.字符串 String 对象_JavaScript

方法二

用反斜杠 \ 链接多行字符

var aa = '<div>\n  \
<h1>hello world!</h1>\n \
</div>';
console.log(aa);

JavaScript 学习-11.字符串 String 对象_数组_02

方法三

可以定义一个数组,然后用join方法转字符串

var aa = [
'<div>',
'<h1>hello world!</h1>',
'</div>'].join('\n');
console.log(aa);

方法四(推荐)

用反引号 ` (就是tab键上方那个)包含多行文本

let aa = `<div>
<h1>hello world!</h1>
</div>`;
console.log(aa);

备注:ES6新增的创建字符串的方式,使用反引号定义。

字符串属性

字符串中属性:

  • constructor 返回创建字符串属性的函数
  • length 返回字符串的长度
  • prototype 允许您向对象添加属性和方法

用的比较多的是length属性统计字符串的长度

var a = 'hello world';
console.log(a.length); // 11

其中空格也算一个字符

字符串中的方法

indexOf() 返回字符串第一次出现的位置

indexOf() 可以传2个参数, 返回出现的位置

  • searchString 必需。规定需检索的字符串值。 |
  • position 可选的整数参数。规定在字符串中开始检索的位置。

统计字符串​​hello world​​​中第一个字符​​l​​出现的位置

var a = 'hello world';
console.log(a.indexOf('l')); // 2

带上第二个参数起始位置5,那么就是从第5个位置往后检索到第一次出现​​l​​的位置

var a = 'hello world';
console.log(a.indexOf('l', 5)); // 9

也可以检索一个单词在字符串中出现的位置

var b = "Hello world, welcome to my blog.";
console.log(b.indexOf('to')) // 21

includes() 查找字符串中是否包含指定字符,

includes()也是传2个参数,只是返回值不一样,返回布尔值。

  • searchString 必需。规定需检索的字符串值。 |
  • position 可选的整数参数。规定在字符串中开始检索的位置。

查找字符串中是否包含'world'

var c = "Hello world, welcome to my blog.";
console.log(c.includes('world')) // true
console.log(c.includes('world', 15)) // false

split() 把字符串分割为子字符串数组

split()传2个参数,返回数组

  • separator 可选。字符串或正则表达式,从该参数指定的地方分割 string Object。
  • limit 可选。该参数可指定返回的数组的最大长度。如果设置了该参数,返回的子串不会多于这个参数指定的数组。如果没有设置该参数,整个字符串都会被分割,不考虑它的长度。

把字符串​​hello_world_yoyo​​​ 按 ​​_​​​ 分割得到 ​​['hello', 'world', 'yoyo']​

var d = "hello_world_yoyo";
console.log(d.split('_')); // ['hello', 'world', 'yoyo']

可以传limit参数指定返回的数组长度

var d = "hello_world_yoyo";
console.log(d.split('_', 2)); // ['hello', 'world']

大小写转换

toLowerCase() 字符串转小写。toUpperCase() 字符串转大写。

var f = "Hello World";
console.log(f.toLowerCase()) // 转小写 hello world
console.log(f.toUpperCase()) // 转大写 HELLO WORLD

其它更多参考菜鸟教程​​https://www.runoob.com/jsref/jsref-obj-string.html​​




举报

相关推荐

0 条评论