Table of Contents
1. substring()
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.
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.
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.
1. indexOf() & includes()
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.
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.
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.
The match() method can retrieve a specified value within a string, or find a match for one or more regular expressions.
其他方法
replace()方法
toLowerCase() & toUpperCase()
模板字符串
组合其法
字符串反转
去除空白行
String转化为数组
Home Web Front-end JS Tutorial Details of JavaScript string practical routines

Details of JavaScript string practical routines

Mar 03, 2017 pm 02:58 PM
javascript

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)
Copy after login

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)
Copy after login

2. slice()

stringObject.slice(start, end)
Copy after login

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)
Copy after login

3. substr()

stringObject.substr(start,length)
Copy after login

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  (目标长度较大的话,以实际截取的长度为准)
Copy after login

4. split()

str.split([separator][, limit])
Copy after login

    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
    Copy after login
  • 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)
Copy after login

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
Copy after login

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: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>if (str.indexOf(&amp;#39;yoursPecifiedStr&amp;#39;) !== -1) { // do something }</pre><div class="contentsignin">Copy after login</div></div> 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])
Copy after login

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,这是一个更趋向人性化的时代嘛)
}
Copy after login
2. lastIndexOf()

stringObject.lastIndexOf(searchValue,fromIndex)
Copy after login

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
Copy after login

search()

stringObject.search(substr)
stringObject.search(regexp)
Copy after login

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
Copy after login

match() method

stringObject.match(substr)
stringObject.match(regexp)
Copy after login

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#"]
Copy after login

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"]
Copy after login

其他方法

replace()方法

stringObject.replace(regexp/substr,replacement)
Copy after login

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
Copy after login

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

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

toLowerCase() & toUpperCase()

stringObject.toLowerCase()
stringObject.toUpperCase()
Copy after login

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

let str = &#39;www.jeffjade.com&#39;
console.log(str.toLowerCase())   // www.jeffjade.com
console.log(str.toUpperCase())   // WWW.JEFFJADE.COM
Copy after login

模板字符串

这个也是 ES6 才引入进来的新语法,来解决传统输出String模板的蹩脚问题;其功能之强大,设计之贴心,着实令人得到极大满足感,好如久旱逢甘霖一般的舒畅。更何况,在当今 MVVM 前端框架大行其道的时代,使用 ES6 语法也是不用自己个儿去操心兼容性问题,对于塑造 Dom Template 更是如虎添翼,令人爱不释手。

对于她的使用,阮一峰在ECMAScript 6 入门有过详细的描述以及示例,在此就不赘述。只需要明白我们可以像这样去操作了,试问爽否?

function ncieFunc() {
  return "四海无人对夕阳";
}
var niceMan = "陈寅恪";
var jadeTalk = `一生负气成今日 \n ${ncieFunc()} ,
语出 ${niceMan} 的《忆故居》。
`
console.log(jadeTalk)
Copy after login

运行之,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;)
}
Copy after login

去除空白行

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;)
}
Copy after login

String转化为数组

1, 转化为一维数组

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

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

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', ','))
Copy after login

运行之,输出结果如下:

[ [ ‘渺渺钟声出远方’, ‘依依林影万鸦藏。’ ],
[ ‘一生负气成今日’, ‘四海无人对夕阳。’ ],
[ ‘破碎山河迎胜利’, ‘残馀岁月送凄凉。’ ],
[ ‘松门松菊何年梦’, ‘且认他乡作故乡。’ ] ]

抗战时期,陈寅恪先生在给傅斯年的信中,说了这样一段话:“弟之生性,非得安眠饱食,不能作文,非是既富且乐,不能作诗,平生偶有安眠饱食之时,故偶可为文,而一生从无既富且乐之日,故总做不好诗。” 虽是以调侃的以言说,恐也是寄之感慨的悟道之语。自由独立的经济生活,是自由思想与独立人格的坚强后盾与实际保障。写博这事儿,也是一样,整日疲于需求之成改,熬时碌碌,生为糊口;偶有的闲时气力,哪儿是能经得起折腾的?唯是在垒码的间隙,略做记录,积而成篇。而这番为得的糊口的奋争,也是希望将来的某天——能有既富且乐之时,谈那些想谈的,做那些想做的事,如此而已。

 以上就是JavaScript 字符串实用常操纪要详情的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

See all articles