【问题标题】:Using str.replace for multiple words对多个单词使用 str.replace
【发布时间】:2019-09-27 21:23:37
【问题描述】:

我正在为记事本缩写创建一个工作工具。由于我工作的公司对下载任何外部工具非常严格,因此我使用了在记事本上构建的 Javascript 和 HTML。

我已经能够替换单个单词,例如当我输入“Vacancy”时,它会返回“VAC”。或者当输入“付款”时,它会返回“PYMT”。我的问题是尝试将多个单词替换为 1 个小缩写。例如“跟进”我想返回“F/U”。对于我发现的空间,它不起作用。

尝试了多种方法,但无法解决这个问题。

这是我用过的代码sn-p

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;
}

【问题讨论】:

  • 你的代码有很多语法错误。但是,请尝试在对象定义中使用引号,例如 var mapObj = {"Follow Up":"F/U" }。然后你可以这样做:str = str.replace(/Follow Up/, function(matched) {return mapObj[matched];});
  • 很多错别字。在第一个正则表达式末尾缺少/,您将function 拼错为fucntion

标签: javascript string replace str-replace


【解决方案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'

【讨论】:

  • new RegExp(Array.from(abbreviation.keys()).join('|'),'g') 如果您从名称动态生成正则表达式,那么您必须确保它们被转义,否则 "Mr." 可能匹配 "Mrs",例如。
  • 真的,@VLAZ。转义正则表达式并非易事,因此我在替换函数中将|| matched 添加到了我的答案中。这样可以确保只有完全匹配才有任何效果。当Mr. 匹配它时,它将导致返回Mrs 而不是undefined,因此该部分字符串将保持不变。
【解决方案2】:

要在对象中包含带有空格的键,您可以将其放在括号中,例如 {["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"));

【讨论】:

  • 你不需要括号,只需要引号。括号用于computed property names,但您使用的是静态字符串,因此无需评估。
  • 哦,有趣。感谢您的来信。
猜你喜欢
  • 2020-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-15
  • 2013-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多