匹配子字符串并在其后剥离所有内容的Javascript [英] Javascript to match substring and strip everything after it

查看:42
本文介绍了匹配子字符串并在其后剥离所有内容的Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在字符串Y中匹配一个子字符串X,并且需要匹配X,然后在Y中剥离其后的所有内容.

I need to match a substring X within string Y and need to match X then strip everything after it in Y.

推荐答案

代码

var text1 = "abcdefgh";
var text2 = "cde";

alert(text1.substring(0, text1.indexOf(text2)));
alert(text1.substring(0, text1.indexOf(text2) + text2.length));

第一个警报不包含搜索文本,第二个警报不包含搜索文本.

First alert doesn't include search text, second one does.

说明

我将解释代码的第二行.

I'll explain the second line of the code.

text1.substring(0, text1.indexOf(text2) + text2.length))

 

text1.substring(startIndex, endIndex)

这段代码将每个字符从startIndex到endIndex,其中0是第一个字符.因此,在我们的代码中,我们从0(开始)搜索并在以下位置结束:

This piece of code takes every character from startIndex to endIndex, 0 being the first character. So In our code, we search from 0 (the start) and end on:

text1.indexOf(text2)

这将返回text2的第一个实例在文本1中的字符位置.

This returns the character position of the first instance of text2, in text 1.

text2.length

这将返回文本2的长度,因此,如果我们希望将其包含在返回值中,可以将其添加到返回索引的长度中,从而获得返回的结果!

This returns the length of text 2, so if we want to include this in our returned value, we add this to the length of the returned index, giving us the returned result!

这篇关于匹配子字符串并在其后剥离所有内容的Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆