I have a string that looks like this:
'"a": "...",
"b": "...",
"c": "...",
"d": "...",
"text": "Part to access and modify",
"f": "...",
"g": "..."'
And i would like to access to the text after '"text":'.
The way I do it now is const text = str.split('"text": ')[1].split('"')[1] and thanks to that I can access and modify my text.
I don’t know if there is a more efficient method but my biggest problem is to succeed in replacing the old text with the new text in the basic structure.
How can i do it please ?
Before:
'"a": "...",
"b": "...",
"c": "...",
"d": "...",
"text": "Part to access and modify",
"f": "...",
"g": "..."'
After:
'"a": "...",
"b": "...",
"c": "...",
"d": "...",
"text": "Modified text",
"f": "...",
"g": "..."'
>Solution :
You can use a lookbehind assertion regex:
let str = `"a": "...",
"b": "...",
"c": "...",
"d": "...",
"text": "Part to access and modify",
"f": "...",
"g": "..."`;
str = str.replace(/(?<="text": ")[^"]+/, 'Modified text');
console.log(str);
It also looks like a part of an object literal, so:
let str = `"a": "...",
"b": "...",
"c": "...",
"d": "...",
"text": "Part to access and modify",
"f": "...",
"g": "..."`;
const obj = JSON.parse(`{${str}}`);
obj.text = 'Modified text';
console.log(JSON.stringify(obj, null, 2).split('\n').slice(1, -1).map(line => line.trim()).join('\n'));