regEx function not does not pass test

Just wondering what could be wrong with my regEx function, is returning false, is there a better or cleaner approach to mimic startsWith as my application has an embedded JS engine that is ecma 1.8.5 spidermonkey

function startsWith(i,s) {
  var regEx = new RegExp("/^"+i+"/");
  console.log(regEx)
  return regEx.test(s);
}


const myString = "hello world";

console.log(startsWith("hello",myString));

update
Is failing to test when special characters in strings also.

startsWith("%^&.h",myString)

>Solution :

There is a much simpler way to achieve this without regex:

function startsWith(i,s) {
  return s.indexOf(i) === 0;
}

const myString = "hello world";

console.log(startsWith("hello",myString));

Leave a Reply