字符串的创建方式
字符串是javascript中的基本类型之一,它对应的类型是String,可以通过两种方式来创建字符串:
通过变量赋值的方式, 创建字符串的基本类型
通过构造方法(String),创建字符串对象
虽然两种方式创建出的字符串表现形式不一样,但在某些场景下,我们需要的是字符串,但不关心它是字符串基本类型还是字符串对象。在这种场景下,字符串的判断就会发生了一点小小的变化。
具体可参照下面代码加深理解:
var s = "abcd1234DCBA"; //推荐的创建字符串方式var s1 = "abcd1234DCBA";var s2 = new String(s); // 通过构造方法创建字符串var s3 = new String(s);console.log(s===s1); //true 具有值类型的特性console.log(s===s2); //false 基本类型和对象不相等console.log(s2===s3); //false 不同的对象不相等console.log(typeof s); // stringconsole.log(typeof s2); // object//判断输入值是否是基本类型字符串function isString(s) { return typeof s === "string"}console.log(isString(s)); //trueconsole.log(isString(s2)); //false//判断输入值是否是字符串(基本类型+字符串对象形式)function isString2(s) { return s != null && typeof s.valueOf() === "string";}console.log(isString2(s)); //trueconsole.log(isString2(s2)); //true字符串的值不变特性
var s = new String("abc");var r = s.toUpperCase();alert(s);// abcs本身是不会发生变化的alert(r);//ABC常用API - 字符串截取
var s = "0123abc401234";console.log(s.indexOf("23")); // 2console.log(s.lastIndexOf("23")); // 10console.log(s.search(/[a-z]+/g)); // 4 检索出现字符的开始位置常用API - 字符串替换
var s = "cat,bat,sat,fat";var res = s.replace("at","NE");console.log(res);//cNE,bat,sat,fat 只替换第一个匹配项var res1 = s.replace(/at/,"NE");console.log(res1); //cNE,bat,sat,fat 还是只替换第一个匹配项var res2 = s.replace(/at/g,"NE");console.log(res2); //cNE,bNE,sNE,fNE 替换所有的匹配项代码二 . 第二个参数是函数
var s = "ab<name>cd";// 模拟HTML对符合 < >进行转义var res = s.replace(/[<>]/g,function(match,index,souStr) {switch(match) {case "<": return "<";case ">": return ">";}});console.log(res); // ab<name>cd代码三. 才有特殊序列字符进行灵活替换
// 针对字符sou,将关键字key用{}扩起来function strong(sou,key) { var re = new RegExp("("+key+")","g"); return sou.replace(re,"{$1}"); //$1 第一个捕获组}console.log(strong(s,"at")); //c{at},b{at},s{at},f{at}// 针对字符sou,将关键字key用{}扩起来 function strong2(sou,key) { var re = new RegExp(key,"g"); return sou.replace(re,"{$&}"); //$& 匹配的字符串 }console.log(strong2(s,"at")); //c{at},b{at},s{at},f{at}常用API - 字符串分组
var s = "cat,bat,sat,fat";var res = s.split(",");console.log(res); //[ "cat", "bat", "sat", "fat" ]var res2 = s.split(/,/);console.log(res2); //[ "cat", "bat", "sat", "fat" ]var res3 = s.split(/,/,2);console.log(res3); //[ "cat", "bat" ] 只返回2组常用API - 字符串匹配
var s = "cat,bat,sat,fat"; var reg = /[a-z](at)/ ;console.log(s.match(reg)); //[ "cat", "at", index: 0, input: "cat,bat,sat,fat" ]var res = s.match(/[a-z](at)/g);console.log(res); //[ "cat", "bat", "sat", "fat" ]常用API - 字符串比较
var s1 = "abc";var s2 = "bcd";var s3 = new String("abc");console.log(s1>s2); //trueconsole.log(s1==s3); //true 将s1与s3.toString()进行比较console.log(s1.localeCompare(s2)); // -1 s1 小于 s2console.log(s1.localeCompare(s3)); // 0 s1的值与s3相等以上内容就是本文给大家分享的javascript正则表达式和字符串RegExp and String(二),希望大家喜欢。