292

I know that I can do like ^= to see if an id starts with something, and I tried using that for this, but it didn't work. Basically, I'm retrieving a URL and I want to set a class for an element for path names that start in a certain way.

Example:

var pathname = window.location.pathname; //gives me /sub/1/train/yonks/459087 

I want to make sure that for every path that starts with /sub/1, I can set a class for an element:

if (pathname ^= '/sub/1') { //this didn't work... ... 
3
  • 1
    /^\/sub\/1.*$/gi.test(pathname) will return a boolean as predicate. Commented Jun 23, 2016 at 14:12
  • 7
    If you're coming here 6 years later (as myself) the original & duplicated post Javascript StartsWith provides a very neat answer, using Ecmascript 6 startWith() function, that seems to have the best performances. Commented Sep 22, 2016 at 7:36
  • 1
    Or elaborating from a very detailed discussions 'bout performance and Thou shall not modify Objects not owned! - something like this maybe? if (pathname.indexOf('/sub/1') === 0) {//Do.} Commented Nov 14, 2018 at 14:21

6 Answers 6

396

Use stringObject.substring

if (pathname.substring(0, 6) == "/sub/1") { // ... } 
Sign up to request clarification or add additional context in comments.

5 Comments

-1: creates an additional, redundant string.
Here is a test case for this: jsperf.com/starts-with/2 . Substring method appears to be the fastest on my machine (with V8).
This can be made more generic like so: var x = "/sub/1"; if (pathname.substring(0, x.length) === x) { // ... };. This way you're no longer reliant on knowing the length of x as it may change.
creates a new string, so it's not ideal, best method is probably to use charAt, if charAt doesn't create a new string itself :)
I would say that it is worth noting that it is creating a string but I don't think it's worth down voting since there isn't an abundance of clearly better alternatives and I would bet that in most cases the creation of a redundant string is not going to be a problem worth worrying about.
192
String.prototype.startsWith = function(needle) { return this.indexOf(needle) === 0; }; 

8 Comments

-1 see comments here for a valid reason not to use this type of implementation: stackoverflow.com/a/1978419/560287
This is the perfect answer (indexOf thing) than the one which is marked as the answer.
In case of false, the performance of this function depends on the length of the string you want to check, which is not expected bahaviour for this use case
In my opnion not the only correct, but the most correct answer in terms of memory usage and speed. And it is also readable, but keep in mind to not modify objects you do not own (or just try to avoid it).
this is the slow way to do this, comparison will continue throughout the whole string, i would not use this if this methods gets called a lot.
|
89

You can use string.match() and a regular expression for this too:

if(pathname.match(/^\/sub\/1/)) { // you need to escape the slashes 

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

5 Comments

Is there any way to dynamically insert a url string in the expr? e.g. escaping the /'s in the url?
@Tjorriemorrie You can use the RegEx class to accomplish this, like var reUrlTester = new RegEx(your_url_string); if(reUrlTester.test(url)) { // use the test-function to see if the url matches.
@Cros Err, you made a typo there, the class is actually "RegExp", so that should be: var matcher = new RegExp(expected);if(matcher.test(actual)){ return true }
While this will work, try to avoid using RegEx if not strictly necessary. It's just a plain fact that RegEx functions are slower than their equivalent literal string functions. So much slower in fact that some official documentation websites actually tell you to avoid it if possible (I think php.net does, for example). I'd recommend the indexOf() or substr() solutions.
match returns an array with matching strings, not the matching string. See developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
41

A little more reusable function:

beginsWith = function(needle, haystack){ return (haystack.substr(0, needle.length) == needle); } 

Comments

26

First, lets extend the string object. Thanks to Ricardo Peres for the prototype, I think using the variable 'string' works better than 'needle' in the context of making it more readable.

String.prototype.beginsWith = function (string) { return(this.indexOf(string) === 0); }; 

Then you use it like this. Caution! Makes the code extremely readable.

var pathname = window.location.pathname; if (pathname.beginsWith('/sub/1')) { // Do stuff here } 

2 Comments

Not really adding anything.
IMHO indexOf searches the whole string if doesn't find an immediate match at its beginning: so its inefficiency grows for very long strings to search in.
2

Have a look at JavaScript substring() method.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.