Home >Web Front-end >JS Tutorial >How to use substring method

How to use substring method

不言
不言Original
2019-01-30 13:57:0932129browse

substring() is a built-in function in JavaScript that can be used to get a substring from a string and return a new substring based on the given parameters. Its usage syntax is such as "string.substring(indexA , [indexB])”.

How to use substring method

The operating environment of this article: Windows 7 system, Dell G3 computer, javascript version 1.8.5.

substring() is a built-in function in JavaScript, which is used to obtain substrings from strings. In this article, we will take a detailed look at the usage of substring.

Let’s take a look at the basic syntax of substring first

string.substring(indexA, [indexB])

indexA - an integer between 0 and 1, less than the length of the string.

indexB (optional) - an integer between 0 and the length of the string.

The substring method returns a new substring based on the given parameters.

Let’s look at a specific example

The code is as follows

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
<script type="text/javascript">

	// 将字符串作为变量
	var string = "sghxdysgcghd"; 
	a = string.substring(0, 4) 
	b = string.substring(1, 6) 
	c = string.substring(5) 
	d = string.substring(0) 

	// 输出新的字符串
	// 给定字符串的一部分
	document.write(a + "<br>"); 
	document.write(b + "<br>"); 
	document.write(c + "<br>"); 
	document.write(d + "<br>"); 					 
</script>
</body>
</html>

The display effect on the browser is as follows:

How to use substring method

Indices always start with 0. If we still make the index negative, it will be considered zero and the index cannot be a decimal, if it is a decimal it will be converted to an integer smaller than it is.

Let’s take a look at the example

The code is as follows

<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>
<script> 
  var string = "sghxdysgcghd"; 
  a = string.substring(-1) 
  b = string.substring(2.5) 
  c = string.substring(2.9) 
  document.write(a + "<br>"); 
  document.write(b + "<br>"); 
  document.write(c + "<br>"); 

</script>       
</body>
</html>

The display effect on the browser is as follows

How to use substring method

This article is here It’s all over here. For more exciting content, you can pay attention to other related column tutorials on the PHP Chinese website! ! !

The above is the detailed content of How to use substring method. For more information, please follow other related articles on the PHP Chinese website!

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