Samantha J T Star
Samantha J T Star

Reputation: 32818

How can I check the start of a string with jQuery?

I currently have:

if ($(this).data('action') == "Editing" || $(this).data('action') == "Create") {
    tinyMCE.init(window.tinyMCEOptions);
}

What I need to do is to check for "Create Menu" or "Create Referene". Basically any data starting with the word "Create".

How can I do this with a wildcard?

Upvotes: 0

Views: 546

Answers (3)

Terry Kernan
Terry Kernan

Reputation: 806

I know this is old now, but I thought it might be worthwhile adding that a check like this could also work:

var s = "Create Menu";
if (s.indexOf("Create") === 0) { // 0 is the start position of the string
    console.log("string begins with Create");
}

Upvotes: 1

Purag
Purag

Reputation: 17071

If these are attributes of the element (as far as we know, it's this), then you can use this:

if( $(this).is("[data-action^='Create']") ){
    tinyMCE.init(window.tinyMCEOptions);
}

$(this).is("[data-action^='Create']") will check if the data-action attribute of the returned element(s) starts with the string Create. It will return true or false. We're using the attribute starts with selector.

Upvotes: 4

wong2
wong2

Reputation: 35750

var s = "Create Menu";  

/^Create/.test(s); // true  

Update:

if($(this).data('action') == "Editing" || /^Create/.test($(this).data('action'))){
}

Upvotes: 2

Related Questions