对多个单词使用str.replace

问题描述 投票:0回答:2

我正在创建用于记事本缩写的工作工具。由于我所工作的公司对下载任何外部工具都非常严格,因此我不得不使用在记事本上构建的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 string replace str-replace
2个回答
1
投票

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'

0
投票

要在对象中包含空格,您可以将其放在{["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"));
© www.soinside.com 2019 - 2024. All rights reserved.