skip to Main Content

The input should have a param of (string, character)

The character occurs twice within the string.

If i have a string called Saturday and the character a is the point of start and end for the substring I want to get. So it should return aturda. Is this possible?

This shouldn’t tied to only a specific string. So if I pass on the string summer it would still work the same and return mm, and for other strings that has two (2) character occurrences.

2

Answers


  1. We can use match() along with the regex pattern (w)[^1]*?1:

    var input = "Saturday";
    var m = input.match(/(w)[^1]*?1/)[0];
    console.log(m);

    The regex pattern used here says to match:

    • (w) any single letter (captured in 1)
    • [^1]*? followed by any letter other than 1, zero or more times
    • 1 followed by the nearest same initial letter
    Login or Signup to reply.
  2. You can split the string by a or the char then remove the first and last element because when the str is splited by a the last and first segment is not between a then concat the string again and if there is not result return empty string.

    const Process = (str, character) => {
      const chars = str.split(character)
    
      chars.pop()
      chars.shift()
    
      if (chars.length === 0) return ''
    
      return `${character}${chars.join(character)}${character}`
    }
    
    console.log(Process("Saturday", 'a'))
    console.log(Process("Summer", 'a'))
    console.log(Process("After", 'a'))
    console.log(Process("Allow", 'a'))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search