Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Access and modify a specific part of a string in javascript

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading