SoFunction
Updated on 2025-03-01

Detailed explanation of the usage of substr, substring, indexOf, lastIndexOf, split, replace in js

The indexOf() method returns the first occurrence of a specified string value in the string.

The lastIndexOf() method returns the last location where the specified string value appears, searching from back to front at the specified location in a string.

The substring() method is used to extract characters in a string between two specified subscripts.

substr(start,length) means to intercept the string of length length starting from the start position

split splits a string into a substring and returns the result as a string array

replace is used to replace some characters in a string, or to replace a substring that matches a regular expression.

substr(start, length) means to intercept the length string starting from the start position.

var src="images/off_1.png";
alert((7,3));

The pop-up value is: off

substring(start, end) represents a string from start to end, including characters at the start position but not characters at the end position.

var src="images/off_1.png";
alert((7,10));

The pop-up value is: off

The indexOf() method returns the first occurrence of a specified string value in the string (from left to right). If there is no match, return -1, otherwise return the subscript value of the string at the first occurrence position.

var src="images/off_1.png";
alert(('t'));
alert(('i'));
alert(('g'));

The pop-up values ​​are: -1,0,3

The lastIndexOf() method returns the first character index value of a character or string that appears from right to left (as opposed to indexOf)

var src="images/off_1.png";
alert(('/'));
alert(('g'));

The pop-up values ​​are: 6, 15

Split a string into a substring and return the result as an array of strings.

Return a string by space splitting

function SplitDemo(){
  var s, ss;
  var s = "The rain in Spain falls mainly in the plain.";
  // Decompose at each space character.  ss = (" ");
  return(ss);
}

:

Used to replace some characters in a string, or replace a substring that matches a regular expression.

Syntax: (regexp, replacement);

parameter:

regexp: Required, schema to be replaced with RegExp object

replacement: Required, replace text or function that generates replacement text

Return value:

A new string, replaced with replacement of the first match of regexp or all matches obtained after all matches.

illustrate:

The replace() method of stringObject performs a search and replace operation. It will look for substrings matching regexp in stringObject and replace those substrings with replacement. If regexp has the global flag g, the replace() method replaces all matching substrings. Otherwise, it only replaces the first matching substring.

The above is a detailed explanation of the usage of substr, substring, indexOf, lastIndexOf, split and replace in js introduced by this article. I hope you like it.