字符串类型在前端开发者看来是使用最频繁的类型之一,网站上可见的各种文案,几乎都是字符串类型的数据,我们经常需要使用的操作无非是这么几点:读取字符串、转换字符串、清空字符串、拼接字符串、截取字符串。
语法Edit
字符串字面量采取以下形式:
'string text'
"string text"
"中文/汉语"
"español"
"English "
"हिन्दी"
"العربية"
"português"
"বাংলা"
"русский"
"日本語"
"ਪੰਜਾਬੀ"
"한국어"
"number"
模板字面量
从 ECMAScript 2015 开始,字符串字面量也可以称为模板字面量:hello world
hello! world!
hello ${who}
escape <a>${who}</a>
字符串不区分单引号‘ ’和双引号“ ”所有的字符串拼接都会识别,如果你的字符串比较长,可分行使用“+”来拼接。
例如:
let longString = "This is a very long string which needs " +
"to wrap across multiple lines because " +
"otherwise my code is unreadable.";
console.log(longString);
=> "This is a very long string which needs to wrap across multiple lines because otherwise my code is unreadable."
或者也可以使用 "" 来告诉浏览器,你需要继续写这个字符串,但需要保证 ""后面是没有任何符号或者是空格的;
例如:
let longString = "This is a very long string which needs \
to wrap across multiple lines because \
otherwise my code is unreadable.";
console.log(longString)
=>"This is a very long string which needs to wrap across multiple lines because otherwise my code is unreadable."
一、charAt() 根据下标查询/访问字符串的某个字符
var str1="age";
console.log(str1.charAt(2)) =>e
还可以使用 [ ] 的形式来访问,中括号填写的是字符串的下标
var str1="age";
console.log(str1[2]) =>e
二、字符串的比较">" , "<" ,"===" ,">=" ,"<=" ,"!=="
1.字母字符串比较
var str1="aa";
var str2="bb";
console.log(str1<str2) =>true
2.数字字符串比较(会比较两个数字的大小)
var str1="10";
var str2="15";
var str3="10";
console.log(str1<str2,str1===str3) =>true,true
基本字符串和字符串对象的区别
请注意区分 JavaScript 字符串对象和基本字符串值 . ( 对于 Boolean 和Numbers 也同样如此.)
var s_prim = "foo";var s_obj = new String(s_prim);
console.log(typeof s_prim); // Logs "string"
console.log(typeof s_obj); // Logs "object"
三、字符串的长度 length
var str="我爱你中国";
console.log(str.length) =>5
四、charCodeAt(index) 返回表示给定索引的字符的Unicode的值。
方法返回0到65535之间的 UTF-16 编码单元匹配 Unicode 编码单元整数,当charCodeAt()括号中没有值时,默认为0;当有参数时,查询的是字符串的索引值, index的值为一个大于等于 0,小于字符串长度的整数
例:
var str="abc";
console.log(str.charCodeAt()) =》97
var str="abc";
console.log(str.charCodeAt(0)) =》97
结果都是一样的,查询到"a"在编码中的位置为97
var str="abc";
console.log(str.charCodeAt(1)) =》98
字母"b"在编码中的位置为98
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。