var str = "This life without regret into China, the next life is still planting flowers.";
var len = str.length;
返回文本在字符串首次出现的索引
//indexOf():从头到尾查找
var str = "This life without regret into China, the next life is still planting flowers"
+ " 此生无悔入华夏,来世还在种花家";
var position = str.indexOf("life");
console.log(position); //5
//indexOf(字符串, 从哪个位置开始检索)
position = str.indexOf("life", 14);
console.log(positon); //46
//未找到
position = str.indexOf("china");
console.log(position); //未找到文本,返回-1
返回文本在字符串最后一次出现的索引
//lastIndexOf():从尾到头查找
var str = "This life without regret into China, the next life is still planting flowers"
+ " 此生无悔入华夏,来世还在种花家";
var position = str.lastIndexOf("life");
console.log(position); //46
var position = str.lastIndexOf("life", 44);
console.log(position); //5
注:两种方法都接受作为检索起始位置的第二个参数
搜索特定值的字符串,并返回匹配的位置,但是无法设置第二个开始位置参数
var str = "This life without regret into China, the next life is still planting flowers"
+ " 此生无悔入华夏,来世还在种花家";
var position = str.search("来");
console.log(position); //85
var str = "此生无悔入华夏,来世还在种花家";
var index = str.slice(8, 11);
console.log(index); // 来世还
// 一个参数:将裁剪字符串的剩余部分
var index = str.slice(8);
console.log(index); // 来世还在种花家
// 可以使用负数作为参数
var index = str.slice(-11, -8);
console.log(index); // 入华夏
var str = "此生无悔入华夏,来世还在种花家";
var index = str.substring(8, 11);
console.log(index); // 来世还
注:substring() 与 slice() 的区别:
???substring() 无法接受负的索引
var str = "此生无悔入华夏,来世还在种花家";
var index = str.substr(4, 10);
console.log(index); //入华夏,来世还在种花
- replace() 只替换首个匹配
- replace() 对大小写敏感,使用正则表达式 /i(大小写不敏感)
- 如需替换所有匹配,请使用正则表达式的 g 标志(用于全局搜索)
- 正则表达式不需要引号
var str, rstr;
str = "It‘s two to two.";
// 用one替代two,replace()只替换首个匹配
rstr = str.replace("two", "one");
console.log(rstr); // It‘s one to two.
// 大小写敏感
rstr = str.replace("Two", "one");
console.log(rstr); // It‘s two to two.
// 使用正则表达式 /i
rstr = str.replace(/Two/i, "one");
console.log(rstr); // It‘s one to two.
// 全部替换 /g
rstr = str.replace(/two/g, "one");
console.log(rstr); // It‘s one to one.
var str = "Love myself";
var text = str.toUpperCase(); // LOVE MYSELF
var str = "Love myself";
var text = str.toLowerCase(); // love myself
var str1 = "梵高";
var str2 = "向日葵";
var text = str1.concat(" ", str2); //梵高 向日葵
// concat()可以用 +连接符 来替换
var text2 = str1 + " " + str2;
注:字符串是不可变的:字符串不能更改,只能替换。故,连接后显示的都是新字符串
var str = " Hello World! ";
alert(str.trim());
// IE8及以下的浏览器
var str = " Hello World! ";
alert(str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ‘‘));
// 或
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ‘‘);
};
var str = " Hello World! ";
alert(str.trim());
警告:IE8及以下不支持
返回字符串中指定下标(位置)的字符串
var str = "HELLO WORLD";
str.charAt(0); // 返回 H
返回字符串中指定索引的字符 unicode 编码
var str = "HELLO WORLD";
str.charCodeAt(0); // 返回 72
var txt = "Hello"; // 字符串
txt.split(""); // 分隔为字符
原文:https://www.cnblogs.com/nadou/p/14043603.html