• JS中字符串的常见属性及方法


    1、属性

    1.1、length

    var txt = "abc 123";
    console.log(txt.length);  // 7

    2、方法

    JS 为字符串内置了许多属性和方法,但这些内置方法都不会改变原有的字符串,只会返回一个新字符串,在 JS 中字符串是固定不变的。

    2.1、返回字符位置(indexOf()

    该方法返回某个指定的字符串值在字符串中首次出现的位置,如果找不到返回 -1

    stringObject.indexOf(searchvalue,fromindex)    //searchvalue必需   fromindex可选,规定在字符串中开始检索的位置,最小为0
    var str="abc efg, aaa";
    var n = str.indexOf("aaa");  
    console.log(n)  //9

    2.2、去除字符串两边空白(trim()

    该方法去除字符串的头尾空格,该方法不会改变原始字符串。该方法在使用上有浏览器限制,如果浏览器不支持,可以使用正则表达式来实现

    var str = "  Runoob  ";
    console.log("--" + str + "--")        //--  Runoob  --
    console.log("--" + str.trim() + "--");  //--Runoob--
    function myTrim(x) {     //当浏览器不支持直接使用时,可以用这个函数实现trim()   return x.replace(/^s+|s+$/gm,''); } var str = myTrim(" Runoob "); console.log("--" + str + "--"); //--Runoob--

    2.3、检索匹配的字符串(search()

    该方法用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串。若找到则返回匹配到的字符串起始位置,索引从0开始,若找不到返回 -1.

    var str = "abc Runoob!"; 
    console.log(str.search("Runoob"));   //4
    console.log(str.search(/Runoob/i));  //4

    2.4、替换匹配到的字符串(replace()

    该方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。

    string.replace(searchvalue,newvalue)
    var str = "Visit Microsoft! Visit Microsoft!";
    var n = str.replace("Microsoft","Runoob");      //Visit Runoob! Visit Microsoft!
    var txt = str.replace(/microsoft/i,"Runoob");  //Visit Runoob! Visit Microsoft!

    2.5、把其他类型转化成字符串(toString()、String())

    toString() : 除了null和undefined之外,其他的类型(数值,布尔,字符串,对象)都有此方法,它返回相应值的字符串表现(并不修改原变量);

    var age = 11;
    var ageAsString = age.toString();   //"11"
    alert(age) //11;
    var found = true;
    var foundAsString = found.toString();  //"true" 
    var arr = [1,2,'a']
    console.log(arr.toString(), typeof arr.toString())  //1,2,a  string

    String() : 在不知道要转换的值是不是null和undefined情况下,还可以用String(),String()能够将任何类型的数值转换成string类型,String()遵循以下原则:

       1.如果只有toString()方法,则调用toString()方法并返回相应的结果;

       2.如果值为null,则返回"null";

       3.如果值为undefined,则返回 "undefined"; 

  • 相关阅读:
    django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
    Error fetching command 'collectstatic': You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. Command 'collectstatic' skipped
    windows 虚拟环境下 安装 mysql 引擎一系列错误处理
    项目概念流程
    pip 使用
    HTTPserver v3.0 版本项目
    GitHub 使用
    git 操作命令详解
    git 忽略部分文件类型的同步
    Python 正则处理_re模块
  • 原文地址:https://www.cnblogs.com/wenxuehai/p/10322031.html
Copyright © 2020-2023  润新知