[英]jQuery/JavaScript regex to match any three first characters followed by an exact string
我需要一個正則表達式來基於下拉列表的值來驗證表單。 但是,該值由PHP隨機生成(但始終為2位數)。
它必須對“ 38 |一個晚上”有效。數字38將會改變。 到目前為止,我有
//return value of dropdown
var priceOption = $("#price_option-4").val();
//make sure it ends with "One Evening"
var oneEvening = priceOption.match(/^ * + 'One Evening' $/);
我以為只要跟着“一個晚上”就可以匹配任何字符串
字符串不能與正則表達式一起使用,您只需要在正則表達式文字內編寫要匹配\\ test的內容,不帶引號。
/^\d{2}\|One Evening$/.test(priceOption);
// ^^^^^^ Begins with two digits
// ^^ Escaped the | meta char.
// ^^^^^^^^^^^^ Then until the end: One Evening
只需使用
/^\d\d\|One Evening$/.test(priceOption);
xx |一個晚上
/^\d{2}\|One Evening$/
/^.+?One Evening$/
分解
// ^ starts with
// . any character
// + quantifier - one or more of preceding character
// ? non-greedy - ensure regex stops at One Evening.
// One Evening = literal text
// $ match end of string.
請注意,我的回答反映了匹配任何字符序列的要求,然后匹配One Evening
。
我認為最好是更具體一些,並確保您肯定有兩個數字字符。
如果可以的話,最好要具體一點。 請嘗試以下操作:
// <start of string> <2 digits> <|One Evening> <end of string>
/^\d{2}\|One Evening$/.test( priceOption );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.