如何使用jQuery检查字符串的开头?

我目前有:

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

我需要做的是检查“创建菜单”或“创建参考”。 基本上任何以“创建”一词开头的数据。

我怎么能用通配符做到这一点?

如果这些是元素的属性(据我们所知,就是this ),那么你可以使用这个:

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

$(this).is("[data-action^='Create']")将检查返回元素的data-action属性是否字符串Create 开头 。 它将返回truefalse 。 我们正在使用属性begin with selector 。

 var s = "Create Menu"; /^Create/.test(s); // true 

更新:

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

我知道现在这已经很老了,但我认为可能值得补充的是,这样的支票也可以起作用:

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