Home >Web Front-end >JS Tutorial >Details of JavaScript string practical routines

Details of JavaScript string practical routines

黄舟
黄舟Original
2017-03-03 14:58:331153browse

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

1. substring()

xString.substring(start,end)

substring() is the most commonly used string interception method. It can receive two parameters (the parameters cannot be Negative value), which are the start position and end position to be intercepted respectively. It will return a new string whose content is all characters from start to end-1. If the end parameter (end) is omitted, it means intercepting from the start position to the 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)

The slice() method is very similar to the substring() method. The two parameters it passes in also correspond to the starting position and the ending position respectively. The difference is that the parameter in slice() can be a negative value. If the parameter is a negative number, the parameter specifies the position starting from the end of the string. That is, -1 refers to the last character of the string.

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)

The substr() method can extract the specified number of characters starting from the start subscript in the string. The return value is a string containing length characters starting from the start of stringObject (including the character pointed to by start). If length is not specified, the returned string contains characters from start to the end of stringObject. In addition, if start is a negative number, it means counting from the end of the string.

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])

    separator specifies the character (string) used to split the string. separator can be a string or a regular expression. If the separator is omitted, an array of the entire string is returned. If separator is an empty string, str will return an array of each character in the original string.
  • limit An integer that limits the number of split fragments returned. The split method still splits each matching separator, but the returned array will only intercept up to limit elements.
  • let str = 'www.jeffjade.com'
    str.split('.')      // ["www", "jeffjade", "com"]
    str.split('.', 1)   // ["www"]
    str.split('.').join('') // wwwjeffjadecom
  • It is said that this function is really easy to use. Many times the character interception requirement depends on a certain character; and the above three functions all need to know its position. Of course we can use
indexOf

and other methods to obtain it. Obviously this is very cumbersome; but using split makes it easier. Search class method

1. indexOf() & includes()

stringObject.indexOf(searchValue,fromIndex)

indexOf() is used to retrieve the position where the specified string value first appears in the string . It can receive two parameters, searchValue represents the substring to be searched, and fromIndex represents the starting position of the search. If omitted, the search will be performed from the starting position.

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(&amp;#39;yoursPecifiedStr&amp;#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.

&#39;Blue Whale&#39;.includes(&#39;blue&#39;); // returns false
&#39;乔峰乔布斯乔帮主&#39;.includes(&#39;乔布斯&#39;); // returns true
if (str.includes(&#39;yoursPecifiedStr&#39;)) {
    // do something(这样写是不是更为人性化?Yeah,这是一个更趋向人性化的时代嘛)
}
2. lastIndexOf()

stringObject.lastIndexOf(searchValue,fromIndex)

lastIndexOf() syntax is similar to indexOf(). It returns the last occurrence position of a specified substring value, and its retrieval order is from Back to front.

let str = &#39;www.jeffjade.com&#39;
console.log(str.lastIndexOf(&#39;.&#39;))     // 12
console.log(str.lastIndexOf(&#39;.&#39;, 1))  // -1
console.log(str.lastIndexOf(&#39;.&#39;, 5))  // 3
console.log(str.lastIndexOf(&#39;.&#39;, 12)) // 12

search()

stringObject.search(substr)
stringObject.search(regexp)

The search() method is used to retrieve a specified substring in a string, or to retrieve a substring that matches a regular expression. It returns the starting position of the first matching substring, or -1 if there is no match.

let str = &#39;www.jeffjade.com&#39;
console.log(str.search(&#39;w&#39;))    // 0
console.log(str.search(/j/g))   // 4
console.log(str.search(/\./g))  // 3

match() method

stringObject.match(substr)
stringObject.match(regexp)

The match() method can retrieve a specified value within a string, or find a match for one or more regular expressions.

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 = &#39;#1a2b3c4d5e#&#39;;
console.log(str.match(&#39;A&#39;));    //返回null
console.log(str.match(&#39;b&#39;));    //返回["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 = &#39;#1a2b3c4d5e#&#39;
console.log(str.match(/h/g))     //返回null
console.log(str.match(/\d/g))    //返回["1", "2", "3", "4", "5"]

其他方法

replace()方法

stringObject.replace(regexp/substr,replacement)

replace()方法用来进行字符串替换操作,它可以接收两个参数,前者为被替换的子字符串(可以是正则),后者为用来替换的文本。

如果第一个参数传入的是子字符串或是没有进行全局匹配的正则表达式,那么replace()方法将只进行一次替换(即替换最前面的),返回经过一次替换后的结果字符串。

let str = &#39;www.jeffjade.com&#39;
console.log(str.replace(&#39;w&#39;, &#39;W&#39;))   // Www.jeffjade.com
console.log(str.replace(/w/, &#39;W&#39;))   // Www.jeffjade.com

如果第一个参数传入的全局匹配的正则表达式,那么replace()将会对符合条件的子字符串进行多次替换,最后返回经过多次替换的结果字符串。

let str = &#39;www.jeffjade.com&#39;
console.log(str.replace(/w/g, &#39;W&#39;))   // WWW.jeffjade.com

toLowerCase() & toUpperCase()

stringObject.toLowerCase()
stringObject.toUpperCase()

toLowerCase()方法可以把字符串中的大写字母转换为小写,toUpperCase()方法可以把字符串中的小写字母转换为大写。

let str = &#39;www.jeffjade.com&#39;
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(&#39;&#39;).reverse().join(&#39;&#39;)
}

去除空白行

String.prototype.removeBlankLines = function () {
	return this.replace(/(\n[\s\t]*\r*\n)/g, &#39;\n&#39;).replace(/^[\n\r\n\t]*|[\n\r\n\t]*$/g, &#39;&#39;)
}

String转化为数组

1, 转化为一维数组

场景是根据某子字符串转化,直接就用 split 就好;如果转换规则不统一,那么请自求多福吧。

let Str = &#39;陈寅恪,鲁迅,钱钟书,胡适,王国维,梁启超,吴宓,季羡林&#39;
let hallAllOfFameArr = Str.split(&#39;,&#39;)
console.log(hallAllOfFameArr)
// ["陈寅恪", "鲁迅", "钱钟书", "胡适", "王国维", "梁启超", "吴宓", "季羡林"]

2, 转化为二维数组

String.prototype.removeBlankLines = function () {
	return this.replace(/(\n[\s\t]*\r*\n)/g, &#39;\n&#39;).replace(/^[\n\r\n\t]*|[\n\r\n\t]*$/g, &#39;&#39;)
}
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)!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn