第2关:substring()方法与indexof()方法的使用 - 姓名查找
时间: 2023-04-28 13:00:53 浏览: 99
substring()方法和indexof()方法是JavaScript中常用的字符串处理方法。
substring()方法可以从一个字符串中截取指定长度的字符串,语法如下:
string.substring(start, end)
其中,start是截取的起始位置,end是截取的终止位置,截取的字符串包含start位置的字符,但不包含end位置的字符。
例如:
var str = "Hello World";
var sub = str.substring(0, 5);
console.log(sub); // 输出:Hello
indexof()方法可以在一个字符串中查找指定字符串的位置,语法如下:
string.indexof(searchvalue, start)
其中,searchvalue是要查找的字符串,start是查找的起始位置,如果找到了,则返回该字符串的位置,否则返回-1。
例如:
var str = "Hello World";
var index = str.indexof("l", 3);
console.log(index); // 输出:9
通过这两个方法,我们可以很方便地实现姓名查找的功能。例如,我们可以把姓名列表保存在一个字符串中,然后通过substring()方法截取每个姓名,再通过indexof()方法查找指定的姓名。
相关问题
substring方法与indexof
substring方法和indexOf方法都是JavaScript中的字符串方法。
substring方法用于从一个字符串中提取指定位置的子字符串。它接受两个参数,第一个参数是起始位置,第二个参数是结束位置(可选)。如果只有一个参数,则从该位置开始提取到字符串末尾。
indexOf方法用于查找一个字符串在另一个字符串中第一次出现的位置。它接受一个参数,即要查找的字符串。如果找到了,返回该字符串在原字符串中的位置;如果没有找到,返回-1。
这两个方法在字符串处理中非常常用,可以帮助我们快速地获取所需的信息。
js字符串查找indexof
在JavaScript中,要判断字符串是否包含某个子字符串,可以使用字符串的indexOf()方法。这个方法返回子字符串在原始字符串中第一次出现的位置索引。
以下是一个示例代码:
```javascript
let str = 'finding substring in string';
let index = str.indexOf('str');
console.log(index); // 11
```
在上面的代码中,我们定义了一个字符串`str`,然后使用indexOf()方法查找子字符串'str'的索引。结果会打印出11,表示子字符串'str'在原始字符串中第一次出现的位置。
另外,indexOf()方法还可以接受一个可选参数fromIndex,用于指定开始查找的位置。如果不传入fromIndex参数,默认从索引0开始查找。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)