美文网首页
字符串整理

字符串整理

作者: Giraffe_00 | 来源:发表于2020-03-23 17:47 被阅读0次

1、使用substring()隐藏手机号

var str = "18223476898"
var myphone = str.substring(0, 3) + '****' + str.substring(7);
console.log(myphone);//182****6898

2、使用toUpperCase() 把字符串转换为大写。

var str = "Hello world!"
console.log(str.toUpperCase())//HELLO WORLD!

使用toLowerCase() 把字符串转换为小写。

var str = "HELLO WORLD!"
console.log(str.toLowerCase())//hello world!

3、使用 split()来分割字符串

var str = "a,b,c"
var arr = str.split(",");
console.log(arr);//["a", "b", "c"]
var arr1 = str.split(",", 1);
console.log(arr1);//["a"]
var arr2 = str.split("");
console.log(arr2);//["a", ",", "b", ",", "c"]

4、使用indexOf()判断是否包含

var str = '1234567890'
console.log(str.indexOf("2") != -1); // true

5、保留小数点后两位

//四舍五入
var num = 2.4461212;
num = num.toFixed(2); // 输出结果为 2.45
//不四舍五入
var num = 2.4461212;
Math.floor(num * 100) / 100  // 输出结果为 2.44

6、统计一个字符串中某个字符或字符串出现的次数

let str = "哈哈-呵呵-嘿嘿";
this.countString(str, "-")// 2

countString(str, s) {
    console.log(str)
    let length = str.length;
    let count = 0;
    let k = 0;
    for (let i = 0; i <= length; i++) {
        if (str.indexOf(s) == (i - k)) {
            str = str.substring(i - k + 1, str.length);
            count++;
            k = i + 1;
        }
    }
    // console.log(s + "出现的次数为" + count + "次");
    return count
}

7、删除字符串开始和末尾的空格

let str = "    Hello world!    "
console.log(str.trim())//Hello world!

8、使用startsWith() 判断字符串是否以指定的字符串开头
注:startsWith() 方法对大小写敏感。

let str = "Hello world";
let n = str.startsWith("Hello");
console.log(n)//true

 //判断第一个字符是否为“你”
let str = "你好 世界";
if (str.startsWith("你")) {
  str = str.substring(1); 
  console.log(str )//好 世界
}

9、使用endsWith() 判断字符串是否以指定的字符串结尾
注:endsWith() 方法对大小写敏感。

let str = "Hello world";
let n = str.endsWith("world");
console.log(n)//true

 //判断最后一个字符是否为“界”
let str = "你好 世界";
if (str.endsWith("界")) {
  str = str.substring(0,str.length() - 1);
  console.log(str )//你好 世
}

10、使用replace()将一个字符串中的特定字符串换成其他字符串
注:string.replace()默认只替换第一个

let str = "Hello world ! Hello world ! ";
console.log(str.replace("Hello","你好"))//你好 world ! Hello world ! 
console.log(str.replace(/Hello/g,"你好"))//你好 world ! 你好 world ! 

相关文章

网友评论

      本文标题:字符串整理

      本文链接:https://www.haomeiwen.com/subject/azcayhtx.html