You can only use indexof?

Time:2020-9-26

We usually use the indexof method to determine whether a string contains a substring. If a substring is found, the position of the first occurrence of the substring is returned. If not found, – 1 is returned

var name ='chuichui'
name.indexOf('chui')   // 0 
name.indexOf('gg')  // -1

Today, I’d like to introduce some new methods in ES6 to determine whether a string contains a substring.

includes

var name ='chuichui'
name.includes('chui')   // true
name.includes('gg')  // false

startsWith()

  • Startswith() returns a Boolean value indicating whether the parameter string is at the head of the source string
var name ='chuichui'
name.startsWith('chui')   // true
name.startsWith('ui')  // false

endWith()

  • Endwith() returns a Boolean value indicating whether the parameter string is at the end of the source string
var name ='chuichui'
name.endWith('chui')   // true
name.endWith('ui')  // true
name.endWith('ch')  // false

supplement

The above three methods all support the second parameter, which indicates the location where the search starts

var name ='chuichui'
//4 means to search from the fifth character (subscript from 0 ️⃣ Start)
name.includes('chui',4)   // true  
name.startWith('ch',4)  // true
name.endWith('ui',4)  // true

Friendly tips

In the future, when judging whether a string contains a substring, you can only use indexof. Include, startswith, endwith are also good choices

last

Well, that’s all I have to share this time. If you think my article is helpful to you, please don’t be stingy with your praise, Amen~

Recommended Today

Deep understanding of HTTP protocol

*Foreword: I’d like to share with you an article about my experience since I developed it, Let’s share a personal understanding of HTTP* -Maojiale😊 What are the methods of HTTP? HTTP 1.0 defines three request methods: get, post and head HTTP1.1 adds five request methods: options, put, delete, trace and connect What are the specific […]