Home >Web Front-end >JS Tutorial >Details of JavaScript string practical routines
JavaScript strings are used to store and manipulate text. Therefore, she is always with you when writing JS code. When you process user input data, when you read or set the properties of DOM objects, when you operate Cookies, when you convert various Dates, and so on. It’s too complicated to count; and her many APIs always make people reluctant to remember them. Since you use them and search them often, it’s better to browse through them, and also reflect the value of the existence of blogs. , hence this summary. String interception
xString.substring(start,end)
let str = 'www.jeffjade.com' console.log(str.substring(0,3)) // www console.log(str.substring(0)) //www.jeffjade.com console.log(str.substring(-2)) //www.jeffjade.com (传负值则视为0)
2. slice()
stringObject.slice(start, end)
let str = 'www.jeffjade.com' console.log(str.slice(0, 3)) // www console.log(str.slice(-3, -1)) // co console.log(str.slice(1, -1)) // www.jeffjade.co console.log(str.slice(2, 1)) // '' (返回空字符串,start须小于end) console.log(str.slice(-3, 0)) // '' (返回空字符串,start须小于end)
3. substr()
stringObject.substr(start,length)
let str = 'www.jeffjade.com' console.log(webStr.substr(1, 3)) // ww. console.log(webStr.substr(0)) // www.jeffjade.com console.log(webStr.substr(-3, 3)) // com console.log(webStr.substr(-1, 5)) // m (目标长度较大的话,以实际截取的长度为准)
4. split()
str.split([separator][, limit])
let str = 'www.jeffjade.com' str.split('.') // ["www", "jeffjade", "com"] str.split('.', 1) // ["www"] str.split('.').join('') // wwwjeffjadecom
and other methods to obtain it. Obviously this is very cumbersome; but using split
makes it easier. Search class method
stringObject.indexOf(searchValue,fromIndex)
let str = 'www.jeffjade.com' console.log(str.indexOf('.')) // 3 console.log(str.indexOf('.', 1)) // 3 console.log(str.indexOf('.', 5)) // 12 console.log(str.indexOf('.', 12)) // -1
Although
indexOf() is used to retrieve the position where the specified string value first appears in the string, many times, it is used to determine whether the specified string value exists in the string. string; so the code will look like this: <pre class="brush:js;toolbar:false;">if (str.indexOf(&#39;yoursPecifiedStr&#39;) !== -1) {
// do something
}</pre>
You must know that in such a scenario, the includes() in the ES6 language is much more elegant; the includes() method is used to determine whether a string is included Contained in another string, returns true if it is, otherwise returns false.
str.includes(searchString[, position])searchString
The substring to be searched. position Optional. The index position of the current string to start searching for substrings; default is 0. It should be noted that includes() is case-sensitive. 'Blue Whale'.includes('blue'); // returns false
'乔峰乔布斯乔帮主'.includes('乔布斯'); // returns true
if (str.includes('yoursPecifiedStr')) {
// do something(这样写是不是更为人性化?Yeah,这是一个更趋向人性化的时代嘛)
}
2. lastIndexOf()
stringObject.lastIndexOf(searchValue,fromIndex)
let str = 'www.jeffjade.com' console.log(str.lastIndexOf('.')) // 12 console.log(str.lastIndexOf('.', 1)) // -1 console.log(str.lastIndexOf('.', 5)) // 3 console.log(str.lastIndexOf('.', 12)) // 12
search()
stringObject.search(substr) stringObject.search(regexp)
let str = 'www.jeffjade.com' console.log(str.search('w')) // 0 console.log(str.search(/j/g)) // 4 console.log(str.search(/\./g)) // 3
match() method
stringObject.match(substr) stringObject.match(regexp)
If the parameter is a substring or a regular expression without global matching, the match() method will perform a match from the beginning. If no result is matched, null will be returned. Otherwise, an array will be returned. The 0th element of the array stores the matching text. In addition, the returned array also contains two object attributes, index and input, which respectively represent the starting character index of the matching text and the stringObject. Reference (i.e. original string).
let str = '#1a2b3c4d5e#'; console.log(str.match('A')); //返回null console.log(str.match('b')); //返回["b", index: 4, input: "#1a2b3c4d5e#"] console.log(str.match(/b/)); //返回["b", index: 4, input: "#1a2b3c4d5e#"]
If the parameter is passed in a regular expression with global matching, then match() will match multiple times from the beginning until the end. If no result is found, null is returned. Otherwise, an array will be returned, which stores all substrings that meet the requirements and has no index and input attributes.
let str = '#1a2b3c4d5e#' console.log(str.match(/h/g)) //返回null console.log(str.match(/\d/g)) //返回["1", "2", "3", "4", "5"]
stringObject.replace(regexp/substr,replacement)
replace()方法用来进行字符串替换操作,它可以接收两个参数,前者为被替换的子字符串(可以是正则),后者为用来替换的文本。
如果第一个参数传入的是子字符串或是没有进行全局匹配的正则表达式,那么replace()方法将只进行一次替换(即替换最前面的),返回经过一次替换后的结果字符串。
let str = 'www.jeffjade.com' console.log(str.replace('w', 'W')) // Www.jeffjade.com console.log(str.replace(/w/, 'W')) // Www.jeffjade.com
如果第一个参数传入的全局匹配的正则表达式,那么replace()将会对符合条件的子字符串进行多次替换,最后返回经过多次替换的结果字符串。
let str = 'www.jeffjade.com' console.log(str.replace(/w/g, 'W')) // WWW.jeffjade.com
stringObject.toLowerCase() stringObject.toUpperCase()
toLowerCase()方法可以把字符串中的大写字母转换为小写,toUpperCase()方法可以把字符串中的小写字母转换为大写。
let str = 'www.jeffjade.com' console.log(str.toLowerCase()) // www.jeffjade.com console.log(str.toUpperCase()) // WWW.JEFFJADE.COM
这个也是 ES6 才引入进来的新语法,来解决传统输出String模板的蹩脚问题;其功能之强大,设计之贴心,着实令人得到极大满足感,好如久旱逢甘霖一般的舒畅。更何况,在当今 MVVM
前端框架大行其道的时代,使用 ES6 语法也是不用自己个儿去操心兼容性问题,对于塑造 Dom Template
更是如虎添翼,令人爱不释手。
对于她的使用,阮一峰在ECMAScript 6 入门有过详细的描述以及示例,在此就不赘述。只需要明白我们可以像这样去操作了,试问爽否?
function ncieFunc() { return "四海无人对夕阳"; } var niceMan = "陈寅恪"; var jadeTalk = `一生负气成今日 \n ${ncieFunc()} , 语出 ${niceMan} 的《忆故居》。 ` console.log(jadeTalk)
运行之,Chrome Console 输出结果如下:
一生负气成今日
四海无人对夕阳 ,
语出 陈寅恪 的《忆故居》。
细看 JavaScript 提供的String Api,还是有蛮多的,也有些许废弃的,也有将在未来版本会出来的;这其中不乏很多也挺有用的,譬如: charAt(x)、charCodeAt(x)、concat(v1, v2,…)、fromCharCode(c1, c2,…) 等等,还有 ES6
对字符串的扩展,比如 字符串的遍历器接口,repeat() 等等,这可以参见 ES6-string,这里就不多赘述。
在实际代码生产中,很多时候需要用这些提供的基本方法,来打出一套组合拳,以解决其需求所需。很显然又可以借助 prototype
属性,将自造的各路拳法,其归置于 String 对象,然后天亮啦。这一步就看个人喜好了,这里抛出一二段,以引大玉。
String.prototype.reverse = function () { return this.split('').reverse().join('') }
String.prototype.removeBlankLines = function () { return this.replace(/(\n[\s\t]*\r*\n)/g, '\n').replace(/^[\n\r\n\t]*|[\n\r\n\t]*$/g, '') }
1, 转化为一维数组
场景是根据某子字符串转化,直接就用 split
就好;如果转换规则不统一,那么请自求多福吧。
let Str = '陈寅恪,鲁迅,钱钟书,胡适,王国维,梁启超,吴宓,季羡林' let hallAllOfFameArr = Str.split(',') console.log(hallAllOfFameArr) // ["陈寅恪", "鲁迅", "钱钟书", "胡适", "王国维", "梁启超", "吴宓", "季羡林"]
2, 转化为二维数组
String.prototype.removeBlankLines = function () { return this.replace(/(\n[\s\t]*\r*\n)/g, '\n').replace(/^[\n\r\n\t]*|[\n\r\n\t]*$/g, '') } String.prototype.strTo2dArr = function(firstSplit, secondSplit){ var contentStr = this.removeBlankLines(), contentStrArr = contentStr.split(firstSplit), resultArr = contentStrArr.map((element) => { return element.split(secondSplit) }) return resultArr } var str = ` 渺渺钟声出远方,依依林影万鸦藏。 一生负气成今日,四海无人对夕阳。 破碎山河迎胜利,残馀岁月送凄凉。 松门松菊何年梦,且认他乡作故乡。 ` console.log(str.strTo2dArr('\n', ','))
运行之,输出结果如下:
[ [ ‘渺渺钟声出远方’, ‘依依林影万鸦藏。’ ],
[ ‘一生负气成今日’, ‘四海无人对夕阳。’ ],
[ ‘破碎山河迎胜利’, ‘残馀岁月送凄凉。’ ],
[ ‘松门松菊何年梦’, ‘且认他乡作故乡。’ ] ]
抗战时期,陈寅恪先生
在给傅斯年的信中,说了这样一段话:“弟之生性,非得安眠饱食,不能作文,非是既富且乐,不能作诗,平生偶有安眠饱食之时,故偶可为文,而一生从无既富且乐之日,故总做不好诗。” 虽是以调侃的以言说,恐也是寄之感慨的悟道之语。自由独立的经济生活,是自由思想与独立人格的坚强后盾与实际保障。写博这事儿,也是一样,整日疲于需求之成改,熬时碌碌,生为糊口;偶有的闲时气力,哪儿是能经得起折腾的?唯是在垒码的间隙,略做记录,积而成篇。而这番为得的糊口的奋争,也是希望将来的某天——能有既富且乐之时,谈那些想谈的,做那些想做的事,如此而已。
以上就是JavaScript 字符串实用常操纪要详情的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!