Parsing floats from a string - javascript

I'd like parse the float numbers of an array how this:
var array = "-51.2132,0.3100";
I tried with match(/\d+/g) but I'd like to take float
Any idea about the regex
Thanks in advance

Regex isn't required here. You can first split the coordinates by , to get the values, the use ParseFloat to cast them. Try this:
var loc = "-51.2132,0.3100".split(',');
var lat = parseFloat(loc[0]); // = -51.2132
var lon = parseFloat(loc[1]); // = 0.31

Try this:
var floats = array.split(',').map(function(e){return parseFloat(e)});
// result:
[-51.2132, 0.31]
What this line does: first, split the array on the comma character:
array.split(',') // ["-51.2132", "0.3100"]
Then, replace each item in that array with a parseFloat(item):
["-51.2132", "0.3100"].map(function(e){ // For each item in the array
return parseFloat(e); // Cast the current value to a float.
}); // [-51.2132, 0.31]

(-?\d+(?:\.\d+)?)
Try this.Grab the match.See demo.
http://regex101.com/r/dZ1vT6/43

Try this one:
var array = "-51.2132,0.3100";
var regex = /-?\d+\.?\d*/g;
var items = array.match(regex);
var numbers = items.map(function (item) {
return parseFloat(item);
});
http://regexr.com/39o6i

Related

How can I join an array of numbers into 1 concatenated number?

How do I join this array to give me expected output in as few steps as possible?
var x = [31,31,3,1]
//expected output: x = 313131;
Use array join method.Join joins the elements of an array into a string, and returns the string. The default separator is comma (,). Here the separator should be an empty string.
var x = [31,31,3,1].join("");
EDIT: To get the result as numeric
const x = +[31,31,3,1].join("");
or
const x = Number([31,31,3,1].join(""));
Javascript join() will give you the expected output as string. If you want it as a number, do this:
var x = [31,31,3,1];
var xAsString = x.join(''); // Results in a string
var xAsNumber = Number(x.join('')); // Results in a number, you can also use +(x.join(''))
I can't think of anything other than
+Function.call.apply(String.prototype.concat, x)
or, if you insist
+''.concat.apply('', x)
In ES6:
+''.concat(...x)
Using reduce:
+x.reduce((a, b) => a + b, '');
Or if you prefer
x.reduce(Function.call.bind(String.prototype.concat), '')
Another idea is to manipulate the array as a string, always a good approach.
+String.prototype.replace.call(x, /,/g, '')
There may be other ways. Perhaps a Google search on "join array javascript" would turn up some obscure function which joins elements of an array.
Your question asks for a number, most of the answers above are going to give you a string. You want something like this.
const number = Number([31,31,3,1].join(""));
Try join() as follows
var x = [31,31,3,1]
var y = x.join('');
alert(y);
Try below.
var x = [31,31,3,1]
var teststring = x.join("");
This will work
var x = [31,31,3,1];
var result = x.join("");

replace parenthesis in javascript

How do you replace parenthesis with javascript.
I have a format like this:
(14.233,72.456),(12.4566,45.345),(12.456,13.567)
How can I get a format like given below:
14.233,72.456#12.4566,45.345#12.456,13.567
I have tried the following:
bounds = bounds.replace(/\)\,\(/g,'#');
bounds = bounds.replace(/\(/g,'');
bounds = bounds.replace(/\)/,'');
Splitting the string up by the delimiters and join them with your new delimiter:
var data = "(14.233,72.456),(12.4566,45.345),(12.456,13.567)";
data = data.slice(1, -1).split('),(').join('#');
Or using RegEx:
var data = "(14.233,72.456),(12.4566,45.345),(12.456,13.567)";
data = data.slice(1, -1).replace(/\),\(/g, '#');
You may try this (matches only float numbers) :
var s = '(14.233,72.456),(12.4566,45.345),(12.456,13.567)';
bounds = s.match(/\d+\.\d+,\d+\.\d+/g).join('#');
s.match(/\d+\.\d+,\d+\.\d+/g) returns :
['14.233,72.456', '12.4566,45.345', '12.456,13.567']
In addition, you might need to deal with an empty string :
bounds = (s.match(/\d+\.\d+,\d+\.\d+/g) || []).join('#');
var string = "(14.233,72.456),(12.4566,45.345),(12.456,13.567)";
var str = string.substring(1, string.length-1).split('),(').join('#');
alert(str);
Try this, which is almost the same as your code:
bounds = bounds.replace(/\),\(/g,'#').replace(/^\(|\)$/g,'');
See here the code working: http://jsfiddle.net/K8ECj/
[Edited to eliminate capture]
You can use .replace("(", "").replace(")", "");

How to get desired javascript string

I have a JavaScript string sentrptg2c#appqueue#sentrptg2c#vwemployees#
I want to get last part of the string: vwemployees through RegExp or from any JavaScript function.
and also want to remove that last keyword from string so that next time string will be like this sentrptg2c#appqueue#sentrptg2c#
I have tried
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
var array = url.split('/');
var lastsegment = array[array.length-1];
and get vwemployees last segment but the string remains the same
sentrptg2c#appqueue#sentrptg2c#vwemployees#
It should be sentrptg2c#appqueue#sentrptg2c# when above code runs.
Please suggest a way to do this in JavaScript
JSFiddle: http://jsfiddle.net/satpalsingh/ykBCG/
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
//Assuming # as seperator
var array = str.split('#');
//Clear empty value in array
var newArray = array.filter(function(v){return v!==''});
var lastsegment = newArray[newArray.length-1];
alert(lastsegment);
//output is "vwemployees"
<script type="text/javascript">
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
var arr = str.split("#");
alert(arr[arr.length-2]);
</script>
split function will do the job for you.
use split() , splice() to remove from array and join() to join them back again
var str="sentrptg2c#appqueue#sentrptg2c#vwemployees#";
var reqvalue=str.split('#');
alert(reqvalue[3]);
reqvalue.splice(3,1);
alert(reqvalue.join('#'))
fiddle here
The split function can help you: http://www.w3schools.com/jsref/jsref_split.asp
yourString.split("#");
You will get an array with your values: sentrptg2c,appqueue,sentrptg2c,vwemployees
After that you just have to remove the last element, and rebuild your string from this array.
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
alert(str);
var arr = str.split('#');
var lastsegment = arr[arr.length-2];
alert(lastsegment);
var new_str = str.replace(lastsegment+'#', '');
alert(new_str);

Substr and explode in JavaScript

I have this:
var result = "(55.6105023, 12.357556299999942)";
I would like to remove the brackets, and i thought that you could do this with substr (remove the first and last char in the string) <- But i can only manage to remove the last char if i know the length.
And then i would like to put the first number 55.6105023 into variable lat and the second 12.357556299999942 to variable lng by using explode() <- but this does not exists in JS
How can i do this?
Use slice(), which can take negative indices and unlike substr() is standardized and works in all browsers:
result.slice(1, -1);
You can use split() for the other part:
var parts = result.slice(1, -1).split(", ");
var lat = parts[0], lng = parts[1];
Alternatively you could use a regex:
var res = /^\(([\d.]+),\s*([\d.]+)\)$/.exec(result);
var lat = res[1], lng = res[2];
Remove the first and last characters by using substr, replace or slice. Use split to split the string into an array on the comma. Like so:
var chunks = result.slice(1, -1).split(", ");
var lat = chunks[0].trim();
var lng = chunks[1].trim();
I've added the trim to make sure all whitespaces are gone.
You can use a regular expression to pull out the numbers:
"(55.6105023, 12.357556299999942)".match(/[\d\.-]+/g);
// returns ["55.6105023", "12.357556299999942"]
The regex will match digits, decimal points and minus signs.
var result = "(55.6105023, 12.357556299999942)";
var substring = result.substring(1, result.length - 1);
var coordinates = substring.split(",");
var lat = coordinates[0];
var lng = coordinates[1];
You can use string manipulation functions like split and slice to parse out the numbers (or even a regular expression with matching groups), and the Number constructor to parse a number from a string:
var parseResult = function(s) {
var ss = s.split(', ');
return [Number(ss[0].slice(1)), Number(ss[1].slice(0, -1))];
};
var x = parseResult('(55.6105023, 12.357556299999942)');
x[0]; // => 55.6105023
x[1]; // => 12.357556299999942
You can do it by using substring and indexOf:
var result = "(55.6105023, 12.357556299999942)";
var lat = result.substring(result.indexOf('(')+1, result.indexOf(','));
var lon = result.substring(result.indexOf(', ')+1, result.indexOf(')'));
alert(lat); // alerts 55.6105023
alert(lon); // alerts 12.357556299999942
Here is another way, which first converts the data into proper JSON and then into a JavaScript array:
str = str.replace('(', '[').replace(')', ']');
var data = JSON.parse(str),
lat = data[0],
lng = data[1];

Quick Problem - Extracting numbers from a string

I need to extract a single variable number from a string. The string always looks like this:
javascript:change(5);
with the variable being 5.
How can I isolate it? Many thanks in advance.
Here is one way, assuming the number is always surrounded by parentheses:
var str = 'javascript:change(5);';
var lastBit = str.split('(')[1];
var num = lastBit.split(')')[0];
Use regular expressions:-
var test = "javascript:change(5);"
var number = new RegExp("\\d+", "g")
var match = test.match(number);
alert(match);
A simple RegExp can solve this one:
var inputString = 'javascript:change(5);';
var results = /javascript:change\((\d+)\)/.exec(inputString);
if (results)
{
alert(results[1]); // 5
}
Using the javascript:change part in the match as well ensures that if the string isn't in the proper format, you wont get a value from the matches.
var str = 'javascript:change(5);', result = str.match(/\((\d+)\)/);
if ( result ) {
alert( result[1] )
}

Categories

Resources