Home > Mobile >  Remove characters from beginning and end of string with jQuery
Remove characters from beginning and end of string with jQuery

Time:04-21

I need to remove characters from a string with jQuery. The string is this right here...

{"id":"Spirits","name":"Spirits"}

I basically want the output to read Spirits (pulling from the "name" value). I'm seeing a lot of answers for either beginning of string using subString or end of string.

But I'm not sure how to do both and ensure that if Spirits is Volvo or whatever, it accounts for that as well.

Any help is GREATLY appreciated.

CodePudding user response:

Get result directly, Using object key and value if output is in JSON format

If Output is in string format then need to parse and then get data using object key and value

// Get directly using output.name If getting JSON output
output = {"id":"Spirits","name":"Spirits"};
console.log('output Name : ', output.name);

// Parse and get output.name If getting String Output
output = '{"id":"Spirits","name":"Spirits"}';
output = JSON.parse(output);
console.log('output Name : ', output.name);

CodePudding user response:

First, we parse the JSON string into a JSON object.

Next, we delete the key-value pair using the key "name".

Then, we recreate the JSON string from the JSON object with stringify.

Finally, we print the results:

let jsonString = '{"id":"Spirits","name":"Spirits"}';
let json = JSON.parse(jsonString);
delete json["name"];
let output = JSON.stringify(json);
console.log(output);

If you want then to obtain just the word of that only element in your object you could:

let jsonString = '{"id":"Spirits","name":"Spirits"}';
let json = JSON.parse(jsonString);
delete json["name"];

let output = JSON.stringify(json);
console.log(output);

output = Object.values(json)[0];
console.log(output);

  • Related