如何使用JavaScript去除JSON中相邻的重复数字前缀?
用JavaScript去除JSON中title字段的相邻重复数字前缀
你需要处理的JSON数据中,每个question对象的title字段存在相邻重复的数字前缀(比如"1. 1. What..."),要把这类重复前缀改成单次,同时保留原有JSON结构,下面是具体实现方案:
实现步骤与代码示例
首先准备你的原始数据(如果是JSON字符串,先通过JSON.parse()转为JS对象):
const originalData = { "question_1": { "type": "string", "title": "1. 1. What did he want to make for dinner?", "enum": [ " a.) He wanted to make some salad and spaghetti", " b.) He wanted to make some pasta salad" ], "required": false }, "question_2": { "type": "string", "title": "2. 2. Did he have the ingredients to make dinner?", "enum": [ " a.) Yes, he had the ingredients", " b.) No, he didn't have the ingredients" ], "required": false }, "question_3": { "type": "string", "title": "3. 3. Where did he go shopping?", "enum": [ " a.) He went to Albertsons", " b.) He went to Albertos" ], "required": false } };
编写处理函数,用正则匹配并替换重复前缀:
function cleanDuplicateTitlePrefix(data) { // 遍历所有question项 Object.keys(data).forEach(key => { const question = data[key]; if (question.title) { // 匹配开头的重复数字前缀,替换为单次 question.title = question.title.replace(/^(\d+\.\s)\1/, '$1'); } }); return data; } // 处理数据(用structuredClone深拷贝避免修改原数据) const processedData = cleanDuplicateTitlePrefix(structuredClone(originalData)); // 查看结果(可选转为格式化的JSON字符串) console.log(JSON.stringify(processedData, null, 2));
正则表达式说明
用到的正则/^(\d+\.\s)\1/:
^:限定匹配字符串的起始位置,确保只处理开头的前缀(\d+\.\s):捕获组,匹配1个及以上数字 + 英文句号 + 空格的组合\1:引用第一个捕获组的内容,匹配和前面完全相同的重复前缀- 替换为
$1:只保留一次捕获到的前缀,去除重复部分
处理后每个title的重复前缀都会被清除,比如"1. 1. What..."会变成"1. What...",同时完全保留原JSON的结构和其他字段内容。
注意事项
- 如果原始数据是JSON字符串,先执行
const data = JSON.parse(jsonStr);转为JS对象再处理 - 若不想修改原始数据,一定要用深拷贝方法(比如
structuredClone、JSON.parse(JSON.stringify(data)))创建副本后再处理 - 该正则仅处理开头的重复数字前缀,不会影响title中间出现的类似内容,符合需求
内容的提问来源于stack exchange,提问作者SHDT
相关产品推荐
相关产品推荐

