Home » Javascript » How to write strip prefix ignore case in Javascript?

How to write strip prefix ignore case in Javascript?

Posted by: admin November 1, 2017 Leave a comment

Questions:

I’d like to implement a function in Javascript that given a string s and a string prefix, if s starts with prefix ignore case, then return s with the prefix stripped, otherwise return s.

Sounds super easy, right? Someone could just suggest

if (s.toLowerCase().startsWith(prefix.toLowerCase())) {
  return s.substr(prefix.length);
}
return s;

This won’t work due to the issue mentioned in this question. Anyone has an idea how to solve it?

Answers:

This may not be the most efficient, but it seems to work by going character by character:

if (s.toLowerCase().startsWith(p.toLowerCase())) {
    var a = [];
    while (s.toLowerCase().length > p.toLowerCase().length) {
        a.unshift(s.slice(-1));
        s = s.slice(0, -1);
    }
    return a.join('');
}
return s;