Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string begins with something? [duplicate]

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...          ...  
like image 658
n00b0101 Avatar asked Nov 19 '09 23:11

n00b0101


People also ask

How do you check if a string begins with?

The startsWith() method returns true if a string starts with a specified string. Otherwise it returns false . The startsWith() method is case sensitive. See also the endsWith() method.

How do you check if a string starts with a certain word in Java?

Java String startsWith() Method The startsWith() method checks whether a string starts with the specified character(s). Tip: Use the endsWith() method to check whether a string ends with the specified character(s).

How do you check if a string starts with a substring in TypeScript?

The startsWith() method in TypeScript checks if a string starts with another specified string. If this is true, then a true is returned. Otherwise, false is returned.


2 Answers

Use stringObject.substring

if (pathname.substring(0, 6) == "/sub/1") {     // ... } 
like image 68
Philip Reynolds Avatar answered Nov 04 '22 11:11

Philip Reynolds


String.prototype.startsWith = function(needle) {     return this.indexOf(needle) === 0; }; 
like image 39
Ricardo Peres Avatar answered Nov 04 '22 09:11

Ricardo Peres