-
解析 JSON 字符串的同时保留某些格式特定的字符串,例如字符串形式的长数字(超过 15 位) 判断是否可能是 JSON 字符串:
通过检查字符串是否以 { 或 [ 开头来决定是否尝试解析。 保留长数字字符串:
在 reviver 中,检查值是否是数字字符串且长度超过 15 位,如果是,保留原始字符串。 使用正则表达式 1+$
确保字符串是纯数字。 解析失败的处理:如果 JSON.parse 抛出错误(非 JSON 格式字符串),直接保留原始值。
改进下
function parseJSONStringValues(input) {
if (typeof input !== 'object' || input === null) {
throw new Error('Input must be a non-null object');
}
return Object.entries(input).reduce((acc, [key, value]) => {
if (typeof value === 'string') {
// 检查是否是 JSON 格式的字符串
const isJSON =
(value.startsWith('{') && value.endsWith('}')) ||
(value.startsWith('[') && value.endsWith(']'));
if (isJSON) {
try {
acc[key] = JSON.parse(value);
} catch {
acc[key] = value; // 解析失败,保留原值
}
} else {
acc[key] = value; // 非 JSON 格式,直接保留原值
}
} else {
acc[key] = value; // 非字符串类型,直接保留原值
}
return acc;
}, {});
}
// 示例对象
const obj = {
name: 'John',
id: 123,
item: JSON.stringify({ name: 'item1', id: "30957204937590724752050928043", code: 3248972394723888 }),
numberString: '123', // 保留为字符串
arrayString: '[1, 2, 3]', // 解析为数组
};
// 使用函数
const parsedObj = parseJSONStringValues(obj);
console.log(parsedObj);
第一版
export function convertJSONStringsInObject(obj) {
return Object.entries(obj).reduce((acc, [key, value]) => {
// 仅尝试解析可能是 JSON 的字符串
if (typeof value === 'string' && (value.startsWith('{') || value.startsWith('['))) {
try {
acc[key] = JSON.parse(value, (key, value) => {
// 如果值是字符串,且长度超过 15 且是数字字符串,保留原始字符串
if (typeof value === 'string' && /^[0-9]+$/.test(value) && value.length > 15) {
return value;
}
return value;
});
} catch {
acc[key] = value; // 如果解析失败,保留原始值
}
} else {
acc[key] = value; // 非 JSON 字符串直接保留
}
return acc;
}, {});
}
高亮富文本
function highlightKeyword(htmlContent, keyword) {
if (!keyword) return htmlContent; // 如果没有关键字,直接返回原始 HTML
// 转义用户输入的关键字,避免正则表达式特殊字符冲突
const escapeRegExp = (str) =>
str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
// 创建匹配关键字的正则表达式
const keywordRegex = new RegExp(`(${escapeRegExp(keyword)})`, "gi");
// 替换逻辑:只处理 HTML 标签外的纯文本
const result = htmlContent.replace(/>([^<]+)</g, (match, text) => {
const highlightedText = text.replace(
keywordRegex,
'<span class="highlight">$1</span>'
);
return `>${highlightedText}<`;
});
return result;
}
0-9 ↩︎
9478

被折叠的 条评论
为什么被折叠?



