How to get substring between two same characters in JavaScript?


I have a string value as abc:language-letters-alphs/EnglishData:7844val: . I want to extract the part language-letters-alphs/EnglishData, the value between first : and second :. Is there a way to do it without storing each substrings on different vars? I want to do it the ES6 way.


You can do this two ways easily. You can choose what suits you best.

Using String#split

Use split method to get your desired text.

The split() method divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array. 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

You can use [ Method but in that you have define the exact indexes of the words you want to extract.

The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.

let str = 'abc:language-letters-alphs/EnglishData:7844val:'

console.log(str.slice(4, 38)) //language-letters-alphs/EnglishData

Source: stackoverflow