我正在将数据从csv文件导入HTML,在location列下会有一系列数字,这些数字可能是"鲍勃的住处";。
var str = document.getElementById("employee_table").innerHTML;
var res = str.replaceAll("1029434329172", "Bob's place");
document.getElementById("employee_table").innerHTML = res;
var str = document.getElementById("employee_table").innerHTML;
var res = str.replaceAll("1032110505696", "Alan's place");
document.getElementById("employee_table").innerHTML = res;
var str = document.getElementById("employee_table").innerHTML;
var res = str.replaceAll("1024004680659", "Sally's place");
document.getElementById("employee_table").innerHTML = res;
var str = document.getElementById("employee_table").innerHTML;
var res = str.replaceAll("1028194015914", "Gilbert's place");
document.getElementById("employee_table").innerHTML = res;
所以它确实有效,这和它得到的一样有效吗?同样的事情可以用更少的线条来完成吗?
一个想法是有一个地方字典,将用户ID与一个地方关联起来,并在替换回调中使用它
const userPlaces = {
"1029434329172": "Bob's place",
"1032110505696": "Alan's place",
"1024004680659": "Sally's place",
"1028194015914": "Gilbert's place",
};
const replaceMap = (map, text) => {
const keys = Object.keys(map);
const reg = new RegExp(keys.join("|"), "g");
return text.replace(reg, match => map[match]);
}
const employeeTable = document.getElementById("employee_table");
employeeTable.innerHTML = replaceMap(userPlaces, employeeTable.innerHTML);
请注意,这是一个快速而肮脏的实现:例如,如果您有一个不是用户ID但与用户ID部分匹配的数字字符串,replaceMap
将替换它
无论如何,我认为将关注点分开是很重要的:在这里,数据放在一个位置,一个处理字符串的函数放在第二位,DOM处理放在第三位。代码中的所有内容都混在一起了,扩展性不好。
每次添加或读取idemployee_table
时,都要搜索它。更好的解决方案是将employee_table的内容临时存储在变量中,并在最后写入。
var element = document.getElementById("employee_table");
var str = element.innerHTML;
str = str.replaceAll("1029434329172", "Bob's place");
str = str.replaceAll("1032110505696", "Alan's place");
str = str.replaceAll("1024004680659", "Sally's place");
str = str.replaceAll("1028194015914", "Gilbert's place");
element.innerHTML = str;
您还可以使用多个替换串接
var str = document.getElementById("employee_table").innerHTML;
str = str.replaceAll("1029434329172", "Bob's place")
.replaceAll("1032110505696", "Alan's place")
.replaceAll("1024004680659", "Sally's place")
.replaceAll("1028194015914", "Gilbert's place");
document.getElementById("employee_table").innerHTML = str;