regex 删除双引号前后的所有空格

h9vpoimq  于 2023-02-20  发布在  其他
关注(0)|答案(5)|浏览(164)

我用下面的公式去掉了“前后“的所有空格,但没有努力。

var test_string = '{" 1 ": "b.) some pasta salad", "   10": "   a.) Yes, some bread", "11  ": "   a.) eggs and toast  " }'
var test_string_format = test_string.replace(/^[ '"]+|[ '"]+$|( ){2,}/g,'$1')
    
console.log(test_string_format)

如何使用regex获得所需的输出?
{"1":"b.) some pasta salad","10":"a.) Yes, some bread","11":"a.) eggs and toast" }

unhi4e5o

unhi4e5o1#

const regex = /(\s*["]\s*)/gm;

var test_string =  = `{" 1 ": "b.) some pasta salad", "   10": "   a.) Yes, some bread", "11  ": "   a.) eggs and toast  " }
`;

console.log(test_string.replace(regex, '"'))
pgx2nnw8

pgx2nnw82#

假设字符串内容始终是有效的JSON,您可以这样做:

var str = '{" 1 ": "b.) some pasta salad", "   10": "   a.) Yes, some bread", "11  ": "   a.) eggs and toast  " }'

const res=JSON.stringify(Object.fromEntries(Object.entries(JSON.parse(str)).map(e=>e.map(e=>e.trim()))))

console.log(res)

我知道,这是一种“愚蠢”的解决方案,但它适用于给定的示例字符串。
代码片段解析JSON字符串,然后将结果对象转换为数组的数组,每个子数组的每个元素都是.trim()-med,在操作结束时,通过.Object.fromEntries()重构对象,并通过JSON.stringify()将其转换回JSON字符串。

0sgqnhkj

0sgqnhkj3#

将零个或多个空格后接引号,再将零个或多个空格后接引号替换为引号:

replaceAll(/ *" */g, '"')
const test_string = '{" 1 ": "b.) some pasta salad", "   10": "   a.) Yes, some bread", "11  ": "   a.) eggs and toast  " }'

const trimmed = test_string.replaceAll(/ *" */g, '"');

console.log(trimmed);
ruoxqz4g

ruoxqz4g4#

const test_string = '{" 1 ": "b.) some pasta salad", "   10": "   a.) Yes, some bread", "11  ": "   a.) eggs and toast  " }';

const test_string_format = test_string.replace(/\s*"\s*/g, '"');

console.log(test_string_format);
  • \s:匹配任何空白字符
  • *:匹配零个或多个prev字符(\s
  • ":匹配双引号字符
up9lanfz

up9lanfz5#

console.log('{" 1 ": "b.) some pasta salad", "   10": "   a.) Yes, some bread", "11  ": "   a.) eggs and toast  " }'
    .replaceAll(/( *\" +)|( +\ *)/ig,'"'))

相关问题