字符串的常用属性和方法
一.常用属性
length
获取字符串的长度
let txt = "Hello js!";
console.log(txt.length); -------> 9
二.常用方法
String
的对象方法
charAt()
根据索引获取索引对应的字符
let txt = "Hello js!";
console.log(txt.charAt(4)); ------> o
charCodeAt()
let txt = "Hello js!";
console.log(txt.charCodeAt(4));------>111
concat()
连接字符串
let txt = "Hello js!";
console.log(txt.concat(111));------>Hello js!111
fromCharCode()
将Unicode
编码转为字符
String.fromCharCode(72,69,76,76,111);----->HELLo
-
indexOf
和lastIndexOf
indexOf
:获取字符第一次出现在字符串里面的索引
lastIndexOf
:获取字符最后一次出现在字符串里面的索引
let txt = "Hello js!";
console.log(txt.indexOf('l')); ------>2
console.log(txt.lastIndexOf('l')); ------>3
includes()
判断字符串里面是否包含匹配的子字符串
let txt = "Hello js!";
console.log(txt.includes('l')) ------>true
console.log(txt.includes('lp'))------->false
match()
查找找到一个或多个正则表达式的匹配
var str="The rain in SPAIN stays mainly in the plain";
console.log(str.match(/in/g));------>["in", "in", "in", "in", "in"]
8.repeat()
复制字符串指定次数,并将它们连接在一起返回
let txt = "Hello js!";
console.log(txt.repeat(2)) ----->Hello js!Hello js!
search()
查找相匹配的子字符串的开始下边。
let txt="my name is blue";
txt.search("blue"); ----->11
slice()
提取字符串的片断,并在新的字符串中返回被提取的部分
let txt="my name is blue";
txt.slice(1,5); ----->y na
split()
把字符串分割为字符串数组
let txt="my name is blue";
txt.split(" ");------["my", "name", "is", "blue"]
-
startsWith()
和endsWith()
startsWith()
:查看字符串是否以指定的子字符串开头endsWith()
:查看字符串是否以指定的子字符串结束
let txt="my name is blue";
txt.startsWith("my") ------> true
txt.endsWith("my") ------> false
-
substr()
和substring()
substr()
:从起始索引号提取字符串中指定数目的字符substring()
:提取字符串中两个指定的索引号之间的字符
let txt="my name is blue";
txt.substr(3,4) ------> 'name'
txt.substring(3.4) ------> 'ns'
-
toLowerCase()
和toUpperCase()
toLowerCase()
:把字符串里面的大写字母变成小写toUpperCase()
:把字符串里面的小写字母变成大写
let txt="My Name Is Blue";
txt.toLowerCase() ------> 'my name is blue'
txt.toUpperCase() ------> 'MY NAME IS BLUE'
trim()
去除字符串两边的空格
let txt=" My Name Is Blue ";
txt.trim()---->'My Name Is Blue'
replace()
在字符串中查找匹配的子串, 并替换与正则表达式匹配的子串
let txt="My Name Is Blue";
txt.replace("My",222)------>'222 Name Is Blue'
HTML
标签包裹着的内容(需要看浏览器的支持力度)
let txt = "Hello js!";
document.write("<p>字体变大: " + txt.big() + "</p>");
document.write("<p>字体缩小: " + txt.small() + "</p>");
document.write("<p>字体加粗: " + txt.bold() + "</p>");
document.write("<p>斜体: " + txt.italics() + "</p>");
document.write("<p>固定定位: " + txt.fixed() + "</p>");
document.write("<p>加删除线: " + txt.strike() + "</p>");
document.write("<p>字体颜色: " + txt.fontcolor("green") + "</p>");
document.write("<p>字体大小: " + txt.fontsize(6) + "</p>");
document.write("<p>下标: " + txt.sub() + "</p>");
document.write("<p>上标: " + txt.sup() + "</p>");
document.write("<p>链接: " + txt.link("http://www.w3cschool.cc") + "</p>");
document.write("<p>闪动文本: " + txt.blink() + "</p>");
效果如下图: