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

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

Javascript - 替換除最后一個定界符之外的所有分隔符

Javascript - 替換除最后一個定界符之外的所有分隔符

RISEBY 2022-09-16 21:27:38
我有這個代碼:var txt = 'DELIMETER is replaced';txt += 'DELIMETER is replaced';txt += 'DELIMETER is replaced';txt += 'DELIMETER is replaced';txt += 'DELIMETER is replaced'; <-- leave this and not replace the last DELIMETERtxt = txt.replace(/DELIMETER/g, "HI");我知道所有有“定界儀”的單詞都將替換為“HI”,但我想要的只是替換“定界儀”的前四個出現,但保留最后一個“定界儀”,而不是替換該詞。如何實現這一點,我必須使用正則表達式?
查看完整描述

3 回答

?
慕田峪4524236

TA貢獻1875條經驗 獲得超5個贊

您可以混合使用正則表達式和 java 腳本。一種這樣的方法是通過使用字符串,然后使用函數在替換時循環訪問匹配項來檢查它是否是最后一次出現。如果匹配項位于末尾,則返回匹配的字符串(定界符),否則,請替換為替換項 (HI)。lastIndexOf


var txt = 'DELIMETER is replaced';

txt += 'DELIMETER is replaced';

txt += 'DELIMETER is replaced';

txt += 'DELIMETER is replaced';

txt += 'DELIMETER is replaced';


const target = "DELIMETER";

const replacement = "HI"

const regex = new RegExp(target, 'g');


txt = txt.replace(regex, (match, index) => index === txt.lastIndexOf(target) ? match : replacement);


console.log(txt)


查看完整回答
反對 回復 2022-09-16
?
繁星淼淼

TA貢獻1775條經驗 獲得超11個贊

首先將文本分成兩部分,最后一個分隔符之前的部分和它之后的所有內容。然后在第一部分中進行替換,并將它們連接在一起。


var txt = 'DELIMETER is replaced';

txt += 'DELIMETER is replaced';

txt += 'DELIMETER is replaced';

txt += 'DELIMETER is replaced';

txt += 'DELIMETER is replaced';


var match = txt.match(/(.*)(DELIMETER.*)/);

if (match) {

  var [whole, part1, part2] = match;

  part1 = part1.replace(/DELIMETER/g, 'OK');

  txt = part1 + part2;

}

console.log(txt);


查看完整回答
反對 回復 2022-09-16
?
眼眸繁星

TA貢獻1873條經驗 獲得超9個贊

只需提前切掉最后一個分隔符即可。

var matches = txt.match(/^(.*)(DELIMETER.*)$/)
txt = matches[1].replace(/DELIMETER/g, "HI") + matches[2]


查看完整回答
反對 回復 2022-09-16
  • 3 回答
  • 0 關注
  • 166 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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