簡體   English   中英

在字符串末尾找到單詞的正則表達式

[英]Regular expression to find a word at the end of the string

我有一個字符串,根據該字符串的結束字符,我需要檢查一個條件。 我已經設法編寫了以下腳本,但是它沒有達到我的預期。

//var receivers_type = "d2845a48f91b29f9d0a6e96858f05d85xing";
var receivers_type = "d21fca8635940e97d0f8e132d806cedaxingpage";
if (/.*xing/.test(receivers_type)) {
    console.log('xing profile');
    flag = 1;
}
if (/.*xingpage/.test(receivers_type)) {
    console.log('xing page');
    flag = 0;
}

receivers_type = "d2845a48f91b29f9d0a6e96858f05d85xing"條件正常運行時。 它只會進入if循環的第一個。 但是,當receivers_type = "d21fca8635940e97d0f8e132d806cedaxingpage"時,這兩種情況都會進入。 您能幫我解決這個問題嗎?

您不需要.*選擇器,因此應使用以下正則表達式

/xing$/  <-- the character $ means that the xing must be at the end of the string

因此,您的代碼將是:

//var receivers_type = "d2845a48f91b29f9d0a6e96858f05d85xing";
var receivers_type = "d21fca8635940e97d0f8e132d806cedaxingpage";
if (/xing$/.test(receivers_type)) {
    console.log('xing profile');
    flag = 1;
}
if (/xingpage$/.test(receivers_type)) {
    console.log('xing page');
    flag = 0;
}

您需要匹配正則表達式中字符串的結尾。

您可以使用“字符串錨定結尾”來完成此操作,這是一個美元字符。

var receivers_type = "d21fca8635940e97d0f8e132d806cedaxingpage";
if (/.*xing$/.test(receivers_type)) {
  console.log('xing profile');
}
if (/.*xingpage$/.test(receivers_type)) {
  console.log('xing page');
}

您可以在此處了解更多信息: http : //www.regular-expressions.info/anchors.html

我建議使用以下表達式:

/xingpage$/

因此,您將擁有:

if (/xingpage$/.test(receivers_type)) {
    console.log('xing page');
    flag = 0;
}

在Javascript中使用match並更改正則表達式:

if(recievers_type.match(/(xingpage)$/)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM