Home > Back-end >  Check whether a given substring is present in a string, if so get the value inside a parenthesis nex
Check whether a given substring is present in a string, if so get the value inside a parenthesis nex

Time:06-01

Say suppose if I have a string str = "Monday (8-12), Wednesday (12-17)"; If Wednesday (substring) is present in the given string, I need to get my output as => 12-17.Please note the substring can be any day of the week (Monday, Tuesday, Wednesday, Thursday, Friday and Saturday). Thanks

CodePudding user response:

You can use a regular expression to find it quickly. We cannot use the usual literal syntax since the regular expression has to be created dynamically (since the day is a variable parameter).

function findTime(day, schedule) {
  const dayRE = new RegExp(`${day} \\((.*?)\\)`);
  const match = dayRE.exec(schedule);
  return match ? match[1] : null;
}

const time = findTime("Wednesday", "Monday (8-12), Wednesday (12-17)");
console.log(time);

CodePudding user response:

  • There are two operations, one is which regex to use, second is how to get the 12-17 when we have validate the string.

  • I suggest that the string like "Date (xx-xx), Date (xx-xx), ..";

The regex I use to test if there is wednesday:

^(.*Wednesday)(.*\((([0-9])([0-9])(-)([0-9])([0-9]))\))
  • I will not explain the regex carefully, it;s upto you

The complete source code and description

    let string = "jhdishd, Wednesday (12-17), thgudhfuids(), jhfsd, dfjshfjkd, fsdujhf";
    let regex = /^(.*Wednesday)(.*\((([0-9])([0-9])(-)([0-9])([0-9]))\))/;
    let result = "";

    //Test the regex
    if (regex.test(string) == true)
    {
        //Split all " ," in the string
        //The array will contain string like : arr[0] Date (xx-xx), ..
        let arrayOfElement = string.split(', ');

        for (let i = 0; i < arrayOfElement.length;   i)
        {
            //Test if the date have wednesday
            if (regex.test(arrayOfElement[i]) == true)
            { 
               //Split the ( in Date (xx,xx))
               arrayOfElement2 = arrayOfElement[i].split("(");

               //The result of arrayOfElement2[1] is xx-xx)
               //Just get the xx-xx and ingore )
               let resultString = arrayOfElement2[1].substring(0, 5);

               result = resultString;
           }
       }
   }
   console.log(result);

Input

jhdishd, Wednesday (12-17), thgudhfuids(), jhfsd, dfjshfjkd, fsdujhf

Output

12-17
  • Update : for monday, tuesday, .., just change the regex, which is wednesday to monday, tuesday, ..
  • Related