简体   繁体   English

如何在 JavaScript 中的两个相同字符之间获取 substring?

[英]How to get substring between two same characters in JavaScript?

I have a string value as abc:language-letters-alphs/EnglishData:7844val: .我有一个字符串值为abc:language-letters-alphs/EnglishData:7844val: I want to extract the part language-letters-alphs/EnglishData , the value between first : and second : .我想提取部分language-letters-alphs/EnglishData ,即 first :和 second :之间的值。 Is there a way to do it without storing each substrings on different vars?有没有办法不将每个子字符串存储在不同的变量上? I want to do it the ES6 way.我想用 ES6 的方式来做。

const str = "abc:language-letters-alphs/EnglishData:7844val:"
const relevantPart = str.split(':')[1]

You can do this two ways easily.你可以很容易地做到这两种方式 You can choose what suits you best.你可以选择最适合你的。

Using String#split使用字符串#split

Use split method to get your desired text.使用 split 方法获取您想要的文本。

The split() method divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array. split()方法将一个 String 划分为一个有序的子字符串列表,将这些子字符串放入一个数组中,并返回该数组。 The division is done by searching for a pattern;划分是通过搜索模式来完成的; where the pattern is provided as the first parameter in the method's call.其中模式作为方法调用中的第一个参数提供。

 let str = 'abc:language-letters-alphs/EnglishData:7844val:'.split(':') console.log(str[1]) //language-letters-alphs/EnglishData

Using String#slice使用字符串#slice

You can use [ Method but in that you have define the exact indexes of the words you want to extract.您可以使用 [ 方法,但您已经定义了要提取的单词的确切indexes

The slice() method extracts a section of a string and returns it as a new string, without modifying the original string . slice()方法提取字符串的一部分并将其作为新字符串返回,而不修改原始字符串

 let str = 'abc:language-letters-alphs/EnglishData:7844val:' console.log(str.slice(4, 38)) //language-letters-alphs/EnglishData

 console.log("abc:language-letters-alphs/EnglishData:7844val:".split(":")[1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM