JAVASCRIPT

[ Solved – 12 Answers ] JAVASCRIPT – How to check if a string “StartsWith” another string?

  • How to check if a string “StartsWith” another string?
jQuery Code
javascript           string              startswith

  • We can use ECMAScript 6’s String.prototype.startsWith() method, but it’s not yet supported in all browsers.
  • We want to use a shim/polyfill to add it on browsers that don’t support it.

if we need shim, use either:

  • String.prototype.startsWith shim, or
  • The es6-shim, which shims as much of the ES6 spec as possible, including String.prototype.startsWith

We can use the following:

jQuery Code
"Hello Wikitechy!".startsWith("He"); // true

var haystack = "Hello Wikitechy";
var prefix = 'orl';
haystack.startsWith(prefix); // false

  • To Use stringObject.substring
jQuery Code
if (pathname.substring(0, 6) == "/sub/1") {
    // ...
}

  • Another alternative with .lastIndexOf:
jQuery Code
haystack.lastIndexOf(needle, 0) === 0
  • This looks backwards through haystack for an occurrence of needle starting from index 0 of haystack. In other words, it only checks if haystack starts with needle.
  • In principle, this should have performance advantages over some other approaches:
  • It doesn’t search the entire haystack.
  • It doesn’t create a new temporary string and then immediately discard it.

jQuery Code
data.substring(0, input.length) === input

  • using regex’s .test method:
jQuery Code
/^He/.test('Hello Wikitechy')

To do this with a dynamic string rather than a hardcoded one (assuming that the string will not contain any regexp control characters):

jQuery Code
new RegExp('^' + needle).test(haystack)

  • Here is an another way of solution:
jQuery Code
if(!String.prototype.startsWith){
    String.prototype.startsWith = function (str) {
        return !this.indexOf(str);
    }
}

"Hello Wikitechy!".startsWith("He"); // true

 var data = "Hello Wikitechy";
 var input = 'He';
 data.startsWith(input); // true
  • Checking whether the function already exists in case a future browser implements it in native code or if it is implemented by another library.
  • For example, the Prototype Library implements this function already.
  • Using ! is slightly faster and more concise than === 0 though not as readable.
READ  [Solved -8 Answers] PHP - how to create a newline character

jQuery Code
var haystack = 'hello Wikitechy';
var needle = 'he';

if (haystack.indexOf(needle) == 0) {
  // Code if string starts with this substring
}

jQuery Code
function startsWith(str, word) {
    return str.lastIndexOf(word, 0) === 0;
}
startsWith("aaa", "a")
true
startsWith("aaa", "ab")
false
startsWith("abc", "abc")
true
startsWith("abc", "c")
false
startsWith("abc", "a")
true
startsWith("abc", "ba")
false
startsWith("abc", "ab")
true

  • And here is endsWith if we need that too:
jQuery Code
function endsWith(str, word) {
    return str.indexOf(word, str.length - word.length) !== -1;
}

jQuery Code
String.prototype.startsWith = function(needle)
{
    return(this.indexOf(needle) == 0);
};

  • We can use string.match() and a regular expression :
jQuery Code
if(pathname.match(/^\/sub\/1/)) {  // you need to escape the slashes

string.match() will return an array of matching substrings if found, otherwise null.

  • A little more reusable function:
jQuery Code
beginsWith = function(needle, haystack){
    return (haystack.substr(0, needle.length) == needle);
}

First, lets extend the string object, we think using the variable ‘string’ is works better than ‘needle’ in the context of making it more readable.

jQuery Code
String.prototype.beginsWith = function (string) {
    return(this.indexOf(string) === 0);
};
  • Then we use it like this:
jQuery Code
var pathname = window.location.pathname;
if (pathname.beginsWith('/sub/1')) {
    // Do stuff here
}

About the author

author

author

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

X