js学习笔记(字符串)

字符串

字符串的转义

let a1 = 'http:\/\/scdn.com'
//使用 \ 转义符

let a2 = 'scdn           .com'
// &nbsp 空格

模板字符

let year = '2010年';
let site = 'scdn';
console.log(`${site}成立于${year}`);
//输出:scdn成立于2010年

标签模板的实例操作

let lessons = [ 
	{ title:'媒体查询响应式布局',author:'大牛' },
	{ title:'flex 弹性盒子', author:'小牛' },
	{ title:'grid 栅格系统', author:'恩歪' }
 ];
 function template( ) {
 	return `<ul>
		${ lessons
			.map( item => `<li>作者:${item.author}, 课程:${item.title}</li>` )
			.join( "" )}
		</ul>`;
 }
 document.body.innerHTML += template( );

字符串的相关方法

  1. 字符的长度及去空格
let a1 = 'scdn.com';
console.log(a1.length);

let a2 = '   scdn.com    '
console.log( a2.trim( ) )
//str.trim( )去掉前后空格,不会去掉中间空格
  1. 大小写
str.toUpperCase( )大写
str.toLowerCase( )小写
  1. 字符串的截取
let str = ‘abcdefg’;
str.slice(1, 3) => bc 
//从索引1截取到索引3(不包含3)

str.substring(1, 3) => bc 
//从索引1截取到索引3(不包含3)

str.substr(1, 3)=> bcd 
//从索引1开始截取3个
str.slice(-3,-1) => ef
//从索引-3截取到索引-1(不包含-1)

str.substring(-3, -1)  => ‘空’
//相当于substring( 0, 0 )

str.substr(-3, 2) => ef
//从索引-3开始截取2位
  1. 字符串的检索
str.indexOf( 'a', n ) 
//从字符串索引n开始检索‘a’,找不到就返回-1,如果找到的是字符号串的起始位置就返回0

str.lastIndexOf( )
//从字符串的最后开始检索

str.startWith( )
//以XX开头的字符串,返回布尔值

str.endsWith( )
//以XX结束的字符串,返回布尔值

str.includes( )
//是否包含XX的字符,返回布尔值
  1. 字符串的替换
str.replace(old, new)
  1. 字符串的重复
    str.repeat( n )
    //重复n次该字符串
    function phone( mobile, len = 5 ) {
    	return 
    		String(mobile).slice(0, 3)
    		+ " * ".repeat(len)
    		+ String(mobile).slice(len + 3)
    };
    console.log( phone(13111111111) );
    => 131*****111
    

    字符串相关的类型转换

    1. 将字符串转为数值
    str*1
    Number(str)
    parseInt('123abc')
    
    1. 数值转换为字符串
    nem + ''
    String(num)
    
    1. 字符串转为数组
    str.split('')
    
    1. 数组转为字符串
    arr.join('')
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值