[英]how to trim and save in variable upto first space in string in javascript
response data in console I'm getting data mixed with latitude, longitude, altitude and speed in a single string.控制台中的响应数据我在单个字符串中获得了与纬度、经度、高度和速度混合的数据。 i want to segregate all 4 in 4 variables.我想将所有 4 个变量分离为 4 个变量。 I'm trying with index of but getting -1 in place of latitude, how to trim it properly我正在尝试使用索引但用-1代替纬度,如何正确修剪它
response data response data响应数据响应数据
Sample data样本数据
["13.8650839 78.5766843 867.699951171875 0.0"]
Expected output预期 output
latitude=13.8650839
longitude=78.5766843
altitude=867.699951171875
speed=0.0
code代码
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var responsedata = this.responseText;
const data = responsedata;
const [latitude, longitude, altitude, speed] = data[0].split(' ');
console.log(latitude, longitude, altitude, speed);
alert(latitude);
}
};
You can split the array at the spaces and assign them to variables like so, refer here to know more about destructuring
您可以在空格处拆分数组并将它们分配给像这样的变量,请参阅此处以了解有关destructuring
的更多信息
const data = '["12.8651929 77.576346 946.1199908085856 0.0"]'; const [latitude, longitude, altitude, speed] = JSON.parse(data)[0].split(' '); console.log(latitude, longitude, altitude, speed);
You can use split method in js to get the array like this您可以在js中使用split方法来获取这样的数组
const str = ['13.8650839 78.5766843 867.699951171875 0.0'];
const words = str[0].split(' ')
console.log(words);
Now you get ouptut like this现在你得到这样的输出
Array ["13.8650839", "78.5766843", "867.699951171875", "0.0"]
Now you can extract easily you data using array index..现在您可以使用数组索引轻松提取数据..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.