亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用正則表達式根據javascript中的條件從字符串的開頭刪除子字符串?

如何使用正則表達式根據javascript中的條件從字符串的開頭刪除子字符串?

紅顏莎娜 2022-08-04 10:33:45
我有一個這樣的字符串term = "Hey there how you doing?"現在,由于API中的一些問題,我有時會在字符串的開頭收到未定義的。term = "#0undefinedHey there how you doing?"或term = "#1undefined Hey there how you doing?"現在,我可以通過執行類似操作來檢查句子開頭是否存在undefinedif(term.indexOf("undefined") == 0) {    //processing logic}但正如你所看到的,有一個存在的地方可以是任何一位數的數字。#nundefinedn我想要一個正則表達式解決方案,以便它忽略并在句子的開頭查找并刪除和。#nundefined#nundefined因此,如果存在,則最終字符串將為undefinedterm = "Hey there how you doing?" // removed #nundefined如何使用正則表達式執行此操作?
查看完整描述

2 回答

?
瀟瀟雨雨

TA貢獻1833條經驗 獲得超4個贊

let s = "#0undefined Hello World!";

console.log(s.replace(/^\#[0-9]*undefined\s*/,''));


const regex = RegExp('^\#[0-9]*undefined');

console.log('Has undefined = ' + regex.test(s));


查看完整回答
反對 回復 2022-08-04
?
慕村225694

TA貢獻1880條經驗 獲得超4個贊

如果 旁邊的此數字對您有意義,您可以嘗試:undefined


const matches = "#1undefined Hey there how you doing?".match(/#([0-9]*)undefined ?(.*)/);

console.log(matches);


這將為您提供下面的數字,而您清理的郵件將位于 。matches[1]matches[2]


如果您只關心消息,則可以像其他用戶建議的那樣使用來清理輸出:.replace


const output = "#1undefinedHey there how you doing?".replace(/#([0-9]*)undefined ?/, '');

console.log(output)

查看完整回答
反對 回復 2022-08-04
  • 2 回答
  • 0 關注
  • 121 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號