Home > Net >  How to properly get the content of the variable is javascript
How to properly get the content of the variable is javascript

Time:09-02

I need alert the content of a text in javascript Eg. Noodles: yes. Rice: No. Beans: No. Milk: Yes. But the code below only alerts " Noodles

var str ='{"value": "{\"text\":\" Noodles: yes. Rice: No. Beans: No. Milk: Yes.\"}" }';
var content = str.split(':')[2];
alert(content);

can someone help me out.

CodePudding user response:

Given the current scenario, you could do this. Its dirty but will get the job done

var str ='{"value": "{\"text\":\" Noodles: yes. Rice: No. Beans: No. Milk: Yes.\"}" }';
const jsonParsed = JSON.parse( str.replace(`"{"`, `{"`).replace(`}"`, `}`) )
alert(jsonParsed.value.text);

CodePudding user response:

Since it is not in proper JSON format, it cannot be directly converted to a JSON object, so string manipulation is required. Of course it is not the best method but you can try a solution like this. I got each element after index 2, removed unnecessary characters, then joined them by joining with ":"

var str ='{"value": "{\"text\":\" Noodles: yes. Rice: No. Beans: No. Milk: Yes.\"}" }';
var content = str.split(':').slice(2).map(item=>{
    return item.replace(/['"}] /g, '')
})
alert(content);
  • Related