How can slice a string within matching characters?

let str = 'axybexaseraszarasxar';

i want string between “a” to next “a” like ‘axybexa’ string is there any way to take it using substring or slice function of string

Answer

You need firstly to detect where the beginning and the end of the substring you want are.

let str = 'axybexaseraszarasxar';

const strBetweenMatches = (st,sep) => {
  const first = st.indexOf(sep);
  const second = st.indexOf(sep,first+1);
  if (second < first) return st.slice(first);
  return st.slice(first,second+1)
}

console.log(strBetweenMatches(str,'a')); // your desired output
console.log(strBetweenMatches(str,'j')); // no match
console.log(strBetweenMatches(str,'z')); // only one match