在javascript中访问和修改字符串的特定部分

问题描述 投票:0回答:2

我有一个看起来像这样的字符串:

'"a": "...",
"b": "...",
"c": "...",
"d": "...",
"text": "Part to access and modify",
"f": "...",
"g": "..."'

我想访问

'"text":'
之后的文本。 我现在这样做的方式是
const text = str.split('"text": ')[1].split('"')[1]
,因此我可以访问和修改我的文本。 我不知道是否有更有效的方法,但我最大的问题是在基本结构中成功地用新文本替换旧文本。

请问我该怎么做?

之前:

'"a": "...",
"b": "...",
"c": "...",
"d": "...",
"text": "Part to access and modify",
"f": "...",
"g": "..."'

之后:

'"a": "...",
"b": "...",
"c": "...",
"d": "...",
"text": "Modified text",
"f": "...",
"g": "..."'
javascript regex string replace
2个回答
0
投票

您可以使用后行断言正则表达式:

let str = `"a": "...",
"b": "...",
"c": "...",
"d": "...",
"text": "Part to access and modify",
"f": "...",
"g": "..."`;

str = str.replace(/(?<="text": ")[^"]+/, 'Modified text');

console.log(str);


0
投票

这看起来像 JSON 内容,最好/最安全的是使用解析器,而不是正则表达式。话虽如此,您可以在此处使用正则表达式,如下所示:

var input = `"a": "...",
"b": "...",
"c": "...",
"d": "...",
"text": "Part to access and modify",
"f": "...",
"g": "..."`;

input = input.replace(/"text":\s*".*?"/, '"text": "Modified text"');
console.log(input);

© www.soinside.com 2019 - 2024. All rights reserved.