qatestprofile
qatestprofile

Reputation: 133

Replace String using javascript

I have a json in a textarea {"request":{"method":"GET","url":"/thing/1"},"response":{"status":200}}

I have a function currently which gets the value from my textarea and replaces

    function setFontText(text) {
        var str=document.getElementById("urls").value;
        var res = str.replace(/"url":"/g, "&quoturl&quot:&quot" + text + "&quot");
        document.getElementById("urls").innerHTML=res;
    }

I am currently replacing only "url:"/ however I would like to completely replace ( The Italicized section ) "url":"/thing/1" but the part in bold is dynamic here so I do not want to hardcode in my code like str.replace(/"url":"/thing/1"/g

Is there a workaround for this ? If the question isn't clear please revert

Upvotes: 0

Views: 99

Answers (2)

charlietfl
charlietfl

Reputation: 171679

Assuming the structure is consistent you can parse the string to object then modify that object and stringify the result

function setFontText(text) {
  const str = document.getElementById("urls").value,
        obj = JSON.parse(str);
  obj.request.url = text;
  document.getElementById("urls").innerHTML = JSON.stringify(obj);
}

setFontText('/MyTest')
<textarea id="urls" cols=60 rows=6>
{"request":{"method":"GET","url":"/thing/1"},"response":{"status":200}}
</textarea>

Upvotes: 3

Mark Baijens
Mark Baijens

Reputation: 13222

When you parse the json to a javascript object you can easily delete or alter properties. After that just generate a new json from the object again.

var json = '{"request":{"method":"GET","url":"/thing/1"},"response":{"status":200}}';
var jsonResult = JSON.parse(json);
jsonResult.request.url = 'newtext';
var newJson = JSON.stringify(jsonResult);
console.log(newJson);

Upvotes: 2

Related Questions