簡體   English   中英

對多個單詞使用 str.replace

[英]Using str.replace for multiple words

我正在為記事本縮寫創建一個工作工具。 由於我工作的公司嚴格下載我使用 Javascript 和 HTML 構建在記事本上的任何外部工具。

我已經能夠替換單個單詞,例如當我輸入“Vacancy”時它返回“VAC”。 或者當輸入“付款”時,它會返回“PYMT”。 我的問題是嘗試將多個單詞替換為 1 個小縮寫。 例如“跟進”我想返回“F/U”。 對於我發現的空間,它不起作用。

嘗試了多種方法,但無法解決這個問題。

這是我使用過的代碼片段

function myFunction() {

var str = document.getElementById("demo").value; 
var mapObj = {
   Payment:"PYMT",
   Vacancy:"VAC", 
str = str.replace(/Payment|Vacancy, fucntion(matched){
  return mapObj[matched];
});
alert(str);
  document.getElementById("demo").value = res;
}

我想做的是添加我的 mabObj 所以它會讀

function myFunction() {

var str = document.getElementById("demo").value; 
var mapObj = {
Follow Up:"F/U"
str = str.replace(/Follow Up|, fucntion(matched){
  return mapObj[matched];
});
alert(str);
  document.getElementById("demo").value = res;
}

JavaScript 對象可以具有包含空格的屬性,但為了這樣做,屬性名稱需要在其周圍加上引號。

也就是說,我建議在這種情況下使用Map ,因為它允許您匹配任何字符串,而不必擔心與對象原型中的屬性的命名沖突。

const abbreviation = new Map([
    ['Follow Up', 'F/U'],
    ['Payment', 'PYMT'],
    ['Vacancy', 'VAC']
]);
const input = 'Payment noise Vacancy noise Follow Up noise Vacancy';
const pattern = new RegExp(Array.from(abbreviation.keys()).join('|'),'g');
const result = input.replace(pattern, (matched) => {
    return abbreviation.get(matched) || matched;
});
console.log(result);  // 'PYMT noise VAC noise F/U noise VAC'

要在 object 中包含帶有空格的鍵,您可以將其放在括號中,例如{["Follow Up"]: "F/U"}

 function replaceKeyWords(str) { var mapObj = { Payment:"PYMT", Vacancy:"VAC", ["Follow Up"]:"F/U", }; str = str.replace(/(Payment|Vacancy|Follow Up)/, function(matched){ return mapObj[matched]; }); return str; } console.log(replaceKeyWords("Payment")); console.log(replaceKeyWords("Vacancy")); console.log(replaceKeyWords("Follow Up"));

暫無
暫無

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

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