紅顏莎娜
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));

慕村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)
添加回答
舉報
0/150
提交
取消