首页 > 解决方案 > 对多个单词使用 str.replace

问题描述

我正在为记事本缩写创建一个工作工具。由于我工作的公司对下载任何我使用的基于记事本的 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;
}

标签: javascriptstringreplacestr-replace

解决方案


JavaScript 对象可以包含带有空格的属性,但为了做到这一点,属性名称需要用引号引起来。

也就是说,我建议Map在这种情况下使用 a ,因为它可以让您匹配任何字符串,而不必担心与对象原型中的属性的命名冲突。

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'

推荐阅读