从反向的JavaScript切片 [英] Javascript slice from reverse

查看:109
本文介绍了从反向的JavaScript切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在给定的条件下分割javascript变量。

条件是如果变量长度为12,它应该切片为2,6,4,如果长度为11,它应该切片为2,5,4 。如何分片?



这是我尝试过的。

代码:

  var new_no =(+ phone_no.slice(0,2)+) - + phone_no.slice (2,7)+  -  + phone_no.slice(7,11); 

如何根据我给定的条件制作长度检查条件和切片?

解决方案

您可以简单地使用 .length 来检查数字的长度,条件将做的伎俩:

  var phone_no =123456789878; 
if(phone_no.length === 11)
var new_no =(+ phone_no.slice(0,2)+) - + phone_no.slice(2,7)+ - + phone_no.slice(7,11);
else if(phone_no.length === 12)
var new_no =(+ phone_no.slice(0,2)+) - + phone_no.slice(2,8)+ - + phone_no.slice(8,12);
else
alert('Invalid Number');

请参阅此处的DEMO

I want to slice the javascript variable in the given condition.

The condition is if the variable is of length 12 it should slice as 2,6,4 and if it is of length 11 it should slice as 2,5,4. How can i slice this.

Here is what i have tried.

Code :

var new_no   = "("+phone_no.slice(0,2)+")-"+phone_no.slice(2,7)+"-"+phone_no.slice(7,11);

How can i make the length checking condition and slice according to my given condition ?

解决方案

You can simply use .length to check the length of the number and then two simple conditions will do the trick:

var phone_no = "123456789878";
if(phone_no.length === 11)
    var new_no   = "("+phone_no.slice(0,2)+")-"+phone_no.slice(2,7)+"-"+phone_no.slice(7,11);
else if(phone_no.length === 12)
    var new_no   = "("+phone_no.slice(0,2)+")-"+phone_no.slice(2,8)+"-"+phone_no.slice(8,12);
else
    alert('Invalid Number');

See the DEMO here

这篇关于从反向的JavaScript切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆