Access and modify a specific part of a string in javascript

55 views Asked by At

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": "..."'
2

There are 2 answers

5
Alexander Nenashev On BEST ANSWER

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'));

0
Tim Biegeleisen On

This looks like JSON content and it would be best/safest to use a parser, rather than regex. That being said, you could use regex here as follows:

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);