user1679941
user1679941

Reputation:

How can I make javascript match the start of a string?

I have the following coce:

if (link.action === "Create") {

However my link.action could be:

Create xxxx 

Is there a way I can change this match so it just checks for the start being "Create" ?

Upvotes: 0

Views: 106

Answers (3)

Lolitha Ratnayake
Lolitha Ratnayake

Reputation: 308

link.action.slice(0,6)=="Create"

Will also work as you like as above mentioned methods. For further read String object reference in java script.

Upvotes: 1

Yograj Gupta
Yograj Gupta

Reputation: 9869

Just Check string.indexOf(string_to_check). It returns the index number for a 'string_to_check', if it exists in the string. Any in your case, you want the string start with "Create", so the index should be always 0 in your case.

So, You can try this

if (link.action.indexOf("Create") == 0) {

Upvotes: 3

Matt Ball
Matt Ball

Reputation: 359956

Use a regular expression.

if (link.action.match(/^Create/) {

}

^ is a special character: an anchor which matches only the beginning of the input.

More reading on regex in general: http://www.regular-expressions.info

Upvotes: 1

Related Questions