JavaScript - 字符串的一些常用方法

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <!-- <script src="js/jquery-1.10.2.min.js"></script> -->
    <script src="js/jquery-3.3.1.min.js"></script>
    <style>

    </style>
</head>

<body>

    <script>
        var str = "i:0#.f|membership|#alex.hou@gds.ey.com";
        // charAt-code出现位置 和 code Unicode编码
        console.log(str.charAt(1));
        console.log(str.charCodeAt(1));

        // indexOf-字符串第一次出现某字母的位置, 第二个参数是左数第几个索引开始找 默认0
        console.log(str.indexOf("#"));
        console.log(str.indexOf("#", 4));

        // match-查找字符串中是否有相同的字符,有的话返回数组,第0位代表匹配的字符,index为第一次匹配到的索引,没有返回null, 如果是正则匹配 加上g是全字符串匹配,不加g是只匹配第一个
        var str = "2 plus!1 2 equal plus! 3 呵呵456";
        console.log(str.match("1"));
        console.log(str.match(/\d+/g));

        // substring- 方法用于提取字符串中介于两个指定下标之间的字符。  一个参数,从指定位置截取至最后, 两个参数,截取两个参数中间之间的字符。
        var str = "i:0#.f|membership|abcd@163.com";
        console.log(str);
        console.log(str.substring(18));
        console.log(str.substring(7, 17));
        // substr-   一个参数的时候和substring用法相同, 两个参数时,第一个参数代表从哪开始, 第二个参数代表从第一个参数之后数截取个数。
        console.log(str);
        console.log(str.substr(18));
        console.log(str.substr(7, 17));
        // replace
        var str = 'cat, bat, sat, fat';
        // replace-两个参数都为字符串的情况 - 在字符串中找到第一个参数,并将第一个参数替换为第二个参数,只替换一次
        var result = str.replace('at', 'xxx');
        console.log(str);
        console.log(result);
        // replace-两个参数,第一个被替换的为正则, 要替换的为字符串,  replace会替换字符串中出现的所有第一个正则参数。
        var result = str.replace(/at/g, 'xxx');
        console.log(str);
        console.log(result);
        // replace-第一个参数为正则,第二个参数为函数。函数里的三个参数分别代表匹配到的字符, 索引位置,以及原始字符串
        var result = str.replace(/at/g, function (match, i, originalText) {
            console.log("原始字符串------" + originalText);
            console.log("找到了:" + match + ' .... ' + "位置:" + i);
            console.log("replaceing....");
            return 'xxx';
        });
        console.log(result);
        // replace-第一个参数为正则,第二个参数为函数。函数不传参时, arguments[0],arguments[1],arguments[2] 分别代表匹配到的字符, 索引位置,以及原始字符串
        var result = str.replace(/at/g, function () {
            console.log(arguments[0] + '  ' + arguments[1] + '  ' + arguments[2]);
            return 'xxx'
        });
        console.log(result);
        // replace-demo function 去除字符串空格
        var str = '  hello world      ';
        console.log(str+"---"+str.length);
        console.log(str.replace(/(^\s*)|(\s*$)/g, '')+"---"+str.replace(/(^\s*)|(\s*$)/g, '').length);
        



        // console.log(str.split("i:0#.f|membership|")[1]);
    </script>
</body>

</html>

参考:https://www.cnblogs.com/l1pe1/p/6197371.html


search
执行一个正则表达式匹配查找。如果查找成功,返回字符串中匹配的索引值。否则返回 -1 。
var index1 = a.search(re);
//index1 = 0
var index2 = b.search(re);
//index2 = -1
slice
提取字符串的一部分,并返回一个新字符串(与 substring 相同)。
var sub_string1 = a.slice(1);
//sub_string1 = “ello”
var sub_string2 = a.slice(1,4);
//sub_string2 = “ell”
split
通过将字符串划分成子串,将一个字符串做成一个字符串数组。
var arr1 = a.split("");
//arr1 = [h,e,l,l,o]
length
返回字符串的长度,所谓字符串的长度是指其包含的字符的个数。
var len = a.length();
//len = 5
toLowerCase
将整个字符串转成小写字母。
var lower_string = a.toLowerCase();
//lower_string = “hello”
toUpperCase
将整个字符串转成大写字母。
var upper_string = a.toUpperCase();
//upper_string = “HELLO”

/*


字符串函数扩充


*/

/*

//去除左边的空格

/
String.prototype.LTrim = function()
{
return this.replace(/(^\s
)/g, “”);
}

/*

//去除右边的空格

/
String.prototype.Rtrim = function()
{
return this.replace(/(\s
$)/g, “”);
}

/*

//去除前后空格

/
String.prototype.Trim = function()
{
return this.replace(/(^\s
)|(\s*$)/g, “”);
}

/*

//得到左边的字符串

*/
String.prototype.Left = function(len)
{

if(isNaN(len)||len==null)
{
len = this.length;
}
else
{
if(parseInt(len)<0||parseInt(len)>this.length)
{
len = this.length;
}
}

return this.substr(0,len);
}

/*

//得到右边的字符串

*/
String.prototype.Right = function(len)
{

if(isNaN(len)||len==null)
{
len = this.length;
}
else
{
if(parseInt(len)<0||parseInt(len)>this.length)
{
len = this.length;
}
}

return this.substring(this.length-len,this.length);
}

/*

//得到中间的字符串,注意从0开始

*/
String.prototype.Mid = function(start,len)
{
return this.substr(start,len);
}

/*

//在字符串里查找另一字符串:位置从0开始

*/
String.prototype.InStr = function(str)
{

if(str==null)
{
str = “”;
}

return this.indexOf(str);
}

/*

//在字符串里反向查找另一字符串:位置0开始

*/
String.prototype.InStrRev = function(str)
{

if(str==null)
{
str = “”;
}

return this.lastIndexOf(str);
}

/*

//计算字符串打印长度

*/
String.prototype.LengthW = function()
{
return this.replace(/[^\x00-\xff]/g,"**").length;
}

/*

//是否是正确的IP地址

*/
String.prototype.isIP = function()
{

var reSpaceCheck = /^(\d+).(\d+).(\d+).(\d+)$/;

if (reSpaceCheck.test(this))
{
this.match(reSpaceCheck);
if (RegExp.$1 <= 255 && RegExp.$1 >= 0
&& RegExp.$2 <= 255 && RegExp.$2 >= 0
&& RegExp.$3 <= 255 && RegExp.$3 >= 0
&& RegExp.$4 <= 255 && RegExp.$4 >= 0)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}

}

/*

//是否是正确的长日期

/
String.prototype.isLongDate = function()
{
var r = this.replace(/(^\s
)|(\s*KaTeX parse error: Undefined control sequence: \d at position 19: …, "").match(/^(\̲d̲{1,4})(-|\/)(\d…/);
if(r==null)
{
return false;
}
var d = new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]);
return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]);

}

/*

//是否是正确的短日期

/
String.prototype.isShortDate = function()
{
var r = this.replace(/(^\s
)|(\s*KaTeX parse error: Undefined control sequence: \d at position 19: …, "").match(/^(\̲d̲{1,4})(-|\/)(\d…/);
if(r==null)
{
return false;
}
var d = new Date(r[1], r[3]-1, r[4]);
return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]);
}

/*

//是否是正确的日期

*/
String.prototype.isDate = function()
{
return this.isLongDate()||this.isShortDate();
}

/*

//是否是手机

*/
String.prototype.isMobile = function()
{
return /^0{0,1}13[0-9]{9}$/.test(this);
}

/*

//是否是邮件

/
String.prototype.isEmail = function()
{
return /^\w+((-\w+)|(.\w+))
@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+)*.[A-Za-z0-9]+$/.test(this);
}

/*

//是否是邮编(中国)

*/

String.prototype.isZipCode = function()
{
return /1{6}$/.test(this);
}

/*

//是否是有汉字

/
String.prototype.existChinese = function()
{
//[\u4E00-\u9FA5]為漢字﹐[\uFE30-\uFFA0]為全角符號
return /2
$/.test(this);
}

/*

//是否是合法的文件名/目录名

*/
String.prototype.isFileName = function()
{
return !/[\/*?|:"<>]/g.test(this);
}

/*

//是否是有效链接

/
String.prototype.isUrl = function()
{
return /^http[s]?😕/([\w-]+.)+[\w-]+([\w-./?%&=]
)?$/i.test(this);
}

/*

//是否是有效的身份证(中国)

*/
String.prototype.isIDCard = function()
{
var iSum=0;
var info="";
var sId = this;

varaCity={11:“北京”,12:“天津”,13:“河北”,14:“山西”,15:“内蒙古”,21:“辽宁”,22:“吉林”,23:“黑龙 江”,31:“上海”,32:“江苏”,33:“浙江”,34:“安徽”,35:“福建”,36:“江西”,37:“山东”,41:“河南”,42:“湖北”,43:“湖南”,44:“广东”,45:“广西”,46:“海南”,50:“重庆”,51:“四川”,52:“贵州”,53:“云南”,54:“西藏”,61:“陕西”,62:“甘肃”,63:“青海”,64:“宁夏”,65:“新疆”,71:“台湾”,81:“香港”,82:“澳门”,91:“国外”};

if(!/^\d{17}(\d|x) / i . t e s t ( s I d ) ) r e t u r n f a l s e ; s I d = s I d . r e p l a c e ( / x /i.test(sId)) { return false; } sId=sId.replace(/x /i.test(sId))returnfalse;sId=sId.replace(/x/i,“a”);
//非法地区
if(aCity[parseInt(sId.substr(0,2))]==null)
{
return false;
}

var sBirthday=sId.substr(6,4)+"-"+Number(sId.substr(10,2))+"-"+Number(sId.substr(12,2));

var d=new Date(sBirthday.replace(/-/g,"/"))

//非法生日
if(sBirthday!=(d.getFullYear()+"-"+ (d.getMonth()+1) + “-” + d.getDate()))
{
return false;
}
for(var i = 17;i>=0;i–)
{
iSum += (Math.pow(2,i) % 11) * parseInt(sId.charAt(17 - i),11);
}

if(iSum%11!=1)
{
return false;
}
return true;

}

/*

//是否是有效的电话号码(中国)

*/
String.prototype.isPhoneCall = function()
{
return /([0-9]{3,4}-[0-9]{3,8}$)|(^[0-9]{3,8}$)|(([0-9]{3,4})[0-9]{3,8} ) ∣ ( 0 0 , 1 13 [ 0 − 9 ] 9 )|(^0{0,1}13[0-9]{9} )(00,113[09]9)/.test(this);
}

/*

//是否是数字

*/
String.prototype.isNumeric = function(flag)
{
//验证是否是数字
if(isNaN(this))
{

return false;
}

switch(flag)
{

case null: //数字
case “”:
return true;
case “+”: //正数
return /(+?|\d?)\d*.?\d+KaTeX parse error: Undefined control sequence: \d at position 62: … /^-\̲d̲*\.?\d+/.test(this);
case “i”: //整数
return /(-?|+?|\d)\d+KaTeX parse error: Undefined control sequence: \d at position 64: … /(^\̲d̲+)|(^+?\d+KaTeX parse error: Undefined control sequence: \d at position 90: … /^[-]\̲d̲+/.test(this);
case “f”: //浮点数
return /(-?|+?|^\d?)\d*.\d+KaTeX parse error: Undefined control sequence: \+ at position 65: … /(^\̲+̲?|^\d?)\d*\.\d+/.test(this);
case “-f”: //负浮点数
return /3\d*.\d$/.test(this);
default: //缺省
return true;
}
}

/*

//是否是颜色(#FFFFFF形式)

*/
String.prototype.IsColor = function()
{
var temp = this;
if (temp=="") return true;
if (temp.length!=7) return false;
return (temp.search(/#[a-fA-F0-9]{6}/) != -1);
}

/*

//转换成全角

*/
String.prototype.toCase = function()
{
var tmp = “”;
for(var i=0;i<this.length;i++)
{
if(this.charCodeAt(i)>0&&this.charCodeAt(i)<255)
{
tmp += String.fromCharCode(this.charCodeAt(i)+65248);
}
else
{
tmp += String.fromCharCode(this.charCodeAt(i));
}
}
return tmp
}

/*

//对字符串进行Html编码

*/
String.prototype.toHtmlEncode = function()
{
var str = this;

str=str.replace(/&/g,"&");
str=str.replace(/</g,"<");
str=str.replace(/>/g,">");
str=str.replace(/’/g,"’");
str=str.replace(/"/g,""");
str=str.replace(/\n/g,"
");
str=str.replace(/\ /g," “);
str=str.replace(/\t/g,”    ");

return str;
}

/*

//转换成日期

*/
String.prototype.toDate = function()
{
try
{
return new Date(this.replace(/-/g, “/”));
}
catch(e)
{
return null;
}
}


  1. \d ↩︎

  2. \x00-\xff ↩︎

  3. - ↩︎

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 字符串是一种常用的数据类型,它由一系列字符组成,可以用来表示文本。JavaScript提供了一些内置方法来操作字符串,包括查找字符串、替换字符串、拆分字符串等等。当然,我很乐意帮助你了解 JavaScript常用字符串方法。以下是一些常用方法: 1. length:返回字符串的长度。 2. indexOf:返回字符串中指定字符或子串的第一次出现的位置。如果没有找到该字符或子串,则返回 -1。 3. lastIndexOf:返回字符串中指定字符或子串最后一次出现的位置。如果没有找到该字符或子串,则返回 -1。 4. charAt:返回指定位置的字符。位置从 0 开始。 5. slice:返回从指定位置开始到指定位置结束的子串。可以接受一个或两个参数。 6. substring:与 slice 方法\u4e00\u6837\uff0c\u4e5f\u53ef\u4ee5\u8fd4\u56de\u4ece\u6307\u5b9a\u4f4d\u7f6e\u5f00\u59cb\u5230\u6307\u5b9a\u4f4d\u7f6e\u7ed3\u675f\u7684\u5b50\u4e32\uff0c\u4f46\u4e0d\u80fd\u63a5\u53d7\u8fd1\u4e24\u4e2a\u53c2\u6570\uff0c\u7a0b\u5e8f\u5458\u5fc5\u987b\u81ea\u884c\u5904\u7406\u3002\n\n7. substr\uff1a\u8fd4\u56de\u6307\u5b9a\u4f4d\u7f6e\u5f00\u59cb\uff0c\u957f\u5ea6\u4e3a\u6307\u5b9a\u6570\u91cf\u7684\u5b57\u7b26\u4e32\u3002\n\n8. replace\uff1a\u4f7f\u7528\u4e00\u4e2a\u5b57\u7b26\u4e32\u66ff\u6362\u53d8\u91cf\u4e2d\u7684\u5176\u4ed6\u5b57\u7b26\u4e32\u3002\n\n9. split\uff1a\u4f7f\u7528\u4e00\u4e2a\u5b57\u7b26\u4e32\u5206\u5272\u539f\u59cb\u5b57\u7b26\u4e32\uff0c\u5e76\u8fd4\u56de\u5206\u5272\u540e\u7684\u5b57\u7b26\u4e32\u6570\u7ec4\u3002\n\n10. toLowerCase\uff1a\u5c06\u5b57\u7b26\u4e32\u8f6c\u6362\u4e3a\u5c0f\u5199\u5b57\u7b26\u4e32\u3002\n\n11. toUpperCase\uff1a\u5c06\u5b57\u7b26\u4e32\u8f6c\u6362\u4e3a\u5927\u5199\u5b57\u7b26\u4e32\u3002\n\n\u4e0a\u8ff0\u65b9\u6cd5\u4e3a JavaScript \u4e2d\u5e38\u7528\u7684\u5b57\u7b26\u4e32\u65b9\u6cd5\uff0c\u53ef\u4ee5\u5bf9\u5b66\u4e60 JavaScript \u5e38\u7528\u7684\u5b57\u7b26\u4e32\u65b9\u6cd5\u8fdb\u884c\u7b80\u5355\u7684\u4e8b\u60c5\u4e2d\u5b9e\u8df5\u3002 ### 回答2: JavaScript中的字符串是由一系列字符组成的文本。在JavaScript中,字符串是一种基本的数据类型,并且在Web开发中使用得非常频繁。字符串常用方法特别重要,因为它们使得对字符串进行各种操作变得非常简单。下面是JavaScript学习手册九:字符串常用方法。 1. charAt() 该方法返回字符串中指定的位置的字符。 2. charCodeAt() 该方法返回字符串中指定字符的Unicode编码。 3. concat() 该方法用于将两个或多个字符串合并为一个新的字符串。 4. indexOf() 该方法用于查找字符串中的某个字符或子字符串,如果找到就返回该字符或子字符串的位置,否则返回-1。 5. lastIndexOf() 该方法与indexOf()方法类似,但是它是从字符串的末尾开始查找。 6. match() 该方法用于在字符串中匹配一个正则表达式,并返回匹配的结果。 7. replace() 该方法用于在字符串中匹配一个正则表达式,并用指定的字符串替换匹配的字符串。 8. search() 该方法用于在字符串中查找指定的字符或子字符串,并返回它们的位置。 9. slice() 该方法用于截取字符串中的一部分,并返回该部分的新字符串。 10. split() 该方法用于将一个字符串分割成一个子字符串数组,并返回该数组。 11. substr() 该方法用于截取字符串中从指定位置开始的指定长度的字符串,并返回该部分的新字符串。 12. substring() 该方法与substr()方法类似,但是它是从指定的两个索引之间截取字符串。 13. toLowerCase() 该方法用于将字符串中的所有字符转换为小写字母。 14. toUpperCase() 该方法用于将字符串中的所有字符转换为大写字母。 以上就是JavaScript字符串常用方法。熟练掌握这些方法可以使得你对字符串的操作变得更加便捷和高效。 ### 回答3: JavaScript 中的字符串是一组文本字符,是操作文本数据的基本方式。在 JavaScript 字符串中,有很多方法可用于处理、转换和操作字符串。以下是 JavaScript 字符串常用方法的介绍: 1. 字符串长度: 使用字符串的 length 属性可以获取字符串的长度,如: "hello world".length。 2. 字符串索引: 字符串中的每个字符都可以通过其索引访问。使用 charAt(index) 方法可以返回指定位置的字符,如:"hello".charAt(1)。 3. 字符串连接: 可以通过 + 运算符将两个字符串连接起来,并返回一个新的字符串。如:"hello" + "world"。 4. 字符串查找: 使用 indexOf(str) 和 lastIndexOf(str) 方法可以查找字符串中指定子字符串的位置。其中,indexOf() 方法字符串的开头开始查找,lastIndexOf() 方法从结尾开始查找,如:"hello world".indexOf("l")。 5. 字符串替换: 使用 replace(subStr, replaceStr) 方法可以将字符串中的子字符串替换为指定字符串,并返回一个新的字符串。如:"hello".replace("h", "H")。 6. 字符串转换: 使用 toUpperCase() 和 toLowerCase() 方法可以将字符串转换为大写或小写字母形式,如:"HeLLo".toUpperCase()。 7. 字符串分割: 使用 split(separator) 方法可以将字符串分割成一个数组,其中 separator 是分割符,如:"hello world".split(" ")。 8. 字符串裁剪: 使用 slice(start, end) 方法可以截取字符串的一部分,并返回一个新的字符串,其中 start 是开始索引,end 是结束索引,如:"hello world".slice(0, 5)。 以上是 JavaScript 字符串常用方法。熟练掌握这些方法,能够更加灵活、高效地操作字符串,在开发中发挥更大的作用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值