javascript - 对多个单词使用 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;
}
解决方案
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'
推荐阅读
- pyspark - Pyspark 将十进制转换为日期
- php - 将 json 对象插入到 oracle db 表 blob 列中
- flask - 如何添加和检索密码而不将它们存储在服务器上
- python - Python:向函数内的可变对象添加属性
- http - 为什么 reqwest HTTP 库返回二进制数据而不是文本正文?
- r - R:避免使用for循环顺序选择一列中的值并使用另一列中的值向量应用函数
- function - lua中的十六进制函数是什么?
- html - Angular 应用程序视图中的 bootstrap 4 元素定位
- python - 在 Python 中打破列表理解
- r - 如何将 R 数值数据框更改为有序因子的数据框?