简体   繁体   中英

How can I get a specific element on a json-like string in javascript?

I'm writing a node.js/angular app and in my backend code I have:

res.json(body);

then in my front end I have:

$scope.countryName = function() {
    $http.get('/get/some/numbers').success(function (data) {
        console.log(JSON.stringify(data));
    })
}

When I put localhost:3000/get/some/numbers in the browser, I see: 2;12;1234;43253242643 . How can I get eg a 3rd value ( 1234 ) and assign it to a variable? Btw, do I need to use a JSON.stringify in the frontend since I'm using res.json(body) in the backend?

That isn't valid JSON but assuming it is a simple string, if you want the nth segment of numbers you would do:

var value = data;
var segment = value.split(';')[n]

where n is the numbered segment you want. so value.split(';')[2] would result in 1234 .

Here is a working example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM