【发布时间】:2021-01-26 01:08:09
【问题描述】:
我必须处理一个基本的查找字符串并添加样式,例如。 <button onclick="copyData(event)" class="${orders.test(match)}">${match}</button> 但我想将相同的方法应用于以下所有四个正则表达式匹配;匹配对应的.css样式。
orders: example: 975612345678. range: 975600000000-975699999999
customers: example: 1712345678901. range: 1700000000000-1799999999999
emails: example: word@test.com, 01234@numbers.tk
items: example: 32101234, 1012345678. range: 00000000-99999999, range: 1000000000-1099999999
我们可以看到它错过了emails 和items 的正则表达式:范围:00000000-99999999。
const orders = /\b9756[0-9]{8}\b/;
const customers = /\b17[0-9]{11}\b/;
const emails = ??
const items = ?? and /\b10[0-9]{8}\b/;
for (var i = 0; i < list.length; i++) {
let text = list[i].textContent;
// Make the regex have boundary characters to ensure that it's checking against the whole number, rather than a part. example: 975612345678. range: 975600000000-975699999999
const orders = /\b9756[0-9]{8}\b/;
list[i].innerHTML = text.replace(
// Replace all number sequences in the text
/\d+/g,
// Replace by checking if the replacement text matches "const orders"(regex) to determine color
(match) => `<button onclick="copyData(event)" class="${orders.test(match)}">${match}</button>`
)
}
/*.true needs to be .orders */
.true {
background-color: green;
}
.orders {
background-color: green;
}
/* corresponding regex "orders, customers, emails and items" needs to match style */
.customers {
background-color: red;
}
.emails {
background-color: blue;
}
.items {
background-color: yellow;
}
谁有解决问题的办法?我在Replace multiple strings with multiple other strings 找到了一些东西,但还没有找到可行的解决方案。 可以通过https://jsfiddle.net/rrggrr/rt96ghw2/14/查看演示
【问题讨论】:
标签: javascript regex replace