Common methods of strings (interception, segmentation, search, calculation)

Common Methods for Strings

substr(start position, length)

intercept string

Length can be omitted, after omitting from the start position to the end

var str = 'www.baidu.com'
//截取www
console.log(str.substr(0,3))

substring(start position, end position)

intercept string

does not contain end position

The end position can be omitted, from the start position to the end after omitting

var str = 'www.baidu.com'
//截取www
console.log(str.substr(0,3))

split() : Split the string and return an array

var strs='www.baidu.com'

var s=strs.split('.')
	s[0]:www
    s[1]:baidu
    s[2]:com

indexOf()

Return the position of the string from left to right 第一次(starting from 0), find the position of the returned subscript, and return -1 if you can't find it

var str = 'www.baidu.com'
var one = strs.indexOf('.')
console.log(one) //3

lastindexOf()

Return the position of the string from left to right 最后一次(starting from 0), find the position of the returned subscript, and return -1 if you can't find it

var str = 'www.baidu.com'
var two = strs.lastindexOf('.')
console.log(two) //9

replace

replace('replaced character','new character') replaces the old character with the new character (replaces the first occurrence of the character)

var strs = 'www.baidu.com'
//把“.”换成“-”
var three=strs.replace('.','-')
console.log(three)//www-baidu.com

eval method

Calculate + - * / % of a string

console.log(eval("1+1")) //2
console.log(eval("1-1")) //0
console.log(eval("1*1")) //1
console.log(eval("1/1")) //1
console.log(eval("1%1")) //0

Guess you like

Origin blog.csdn.net/weixin_45753871/article/details/109453237