js中字符串常用的方法

字符串截取:

1.slice(start,end)//参数可以负数 同为正start>end 不交换位置 得到空串

2.substr(start,length)//第一个参数可以负数

3.substring(start,end) //end<start 交换位置 两个参数负数转换为0处理

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
 
</body>
</html>
<script type="text/javascript">
	let str="yangdongxu";
	let a=str.substr(1,3);//substr(start,length)  ang
	//substr(start,end)//第一个参数开始位置,可以是负数,第二个参数是长度length 
    let b=str.substring(1,3);//an
    let b_1=str.substring(3,-1);//yan
   /* substring(start,end)第一个参数开始位置,第二个是结束位置不包括end  
      start>end那么该方法在提取子串之前会先交换这两个参数。负数转换为0 str.substring(3,-1)===str.substring(3,0)===str.substring(0,3)*/
    let c=str.slice(1,3); //an
    let c_1=str.slice(3,1); //空串
    /*slice(start,end)//第一个参数开始位置,第二个是结束位置不包括end 
    */
    console.log(a);//ang
    console.log("b_1:"+b_1);//an
    console.log(b);//an
    console.log(c);//an
    console.log(c_1);//空串
</script>

4.字符串标题替换关键字:

<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>
   
</body>
</html>
<script type="text/javascript">
  const word=["php","css"];
  const string="我喜欢学习php,和css";
  let replceStr=word.reduce((pre,current)=>{
    return pre.replace(current,`<a href="?w=${current}">${current}</a>`)
  },string)
  console.log(replceStr);//我喜欢学习<a href="?w=php">php</a>,和<a href="?w=css">css</a>
  document.body.innerHTML=replceStr;
</script>

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值