简体   繁体   English

对多个单词使用 str.replace

[英]Using str.replace for multiple words

I am creating a work tool for notepad abbreviations.我正在为记事本缩写创建一个工作工具。 As the company I work for is strict about downloading any external tools I've resorted to using Javascript and HTML built on notepad.由于我工作的公司严格下载我使用 Javascript 和 HTML 构建在记事本上的任何外部工具。

I've been able to replace single words such as when I type "Vacancy" it returns "VAC".我已经能够替换单个单词,例如当我输入“Vacancy”时它返回“VAC”。 Or when typing "Payment" it returns "PYMT".或者当输入“付款”时,它会返回“PYMT”。 My issue is trying to replace multiple words into 1 small abbreviation.我的问题是尝试将多个单词替换为 1 个小缩写。 For instance "Follow Up" I want to return "F/U".例如“跟进”我想返回“F/U”。 With the spaces I'm finding it is not working.对于我发现的空间,它不起作用。

Tried multiple ways but unable to figure this out.尝试了多种方法,但无法解决这个问题。

Here is the code snippet that I've used这是我使用过的代码片段

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

What I would like to do is add my mabObj so it would read我想做的是添加我的 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 objects can have properties with spaces in them, but in order to do so, the property name needs to have quotes around it. JavaScript 对象可以具有包含空格的属性,但为了这样做,属性名称需要在其周围加上引号。

That said, I would suggest using a Map in this case, as it will allow you to match any string without worrying about naming collisions with properties from the object's prototype.也就是说,我建议在这种情况下使用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'

To include a key with a space in an object you can put it in brackets like {["Follow Up"]: "F/U"}要在 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