Substr and explode in JavaScript - 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];

Related

Extract words with RegEx

I am new with RegEx, but it would be very useful to use it for my project. What I want to do in Javascript is this :
I have this kind of string "/this/is/an/example" and I would like to extract each word of that string, that is to say :
"/this/is/an/example" -> this, is, an, example. And then use each word.
Up to now, I did :
var str = "/this/is/a/test";
var patt1 = /\/*/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
and it returns me : /,,,,,/,,,/,,/,,,,,
I know that I will have to use .slice function next if I can identify the position of each "/" by using search for instance but using search it only returns me the index of the first "/" that is to say in this case 0.
I cannot find out.
Any Idea ?
Thanks in advance !
Use split()
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
var str = "/this/is/a/test";
var array = str.split('/');
console.log(array);
In case you want to do with regex.
var str = "/this/is/a/test";
var patt1 = /(\w+)/g;
var result = str.match(patt1)
console.log(result);
Well I guess it depends on your definition of 'word', there is a 'word character' match which might be what you want:
var patt1 = /(\w+)/g;
Here is a working example of the regex
Full JS example:
var str = "/this/is/a/test";
var patt1 = /(\w+)/g;
var match = str.match(patt1);
var output = match.join(", ");
console.log(output);
You can use this regex: /\b[^\d\W]+\b/g, to have a specific word just access the index in the array. e.g result[0] == this
var str = "/this/is/a/test";
var patt1 = /\b[^\d\W]+\b/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
<span id="demo"></span>

Parsing floats from a string

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

slice string into two variables

I have coordinates in my attribute data-coordinates
<a class="cor" href="#" data-coordinates="37.650621, 55.740887"></a>
I need slice them into two variables, like this
<script>
//this must contain coordinate which is before ","
var firstCor = $('.cor').attr('data-coordinates');
//this must contain coordinate which is after ","
var lastCor = $('.cor').attr('data-coordinates');
</script>
So then, I must have two variable from one data-coordinates
Use .split()
var cor = $('.cor').data('coordinates').split(','); // creates an array of result
var firstCor = cor[0].trim(); // access 1st value index starts from 0
var lastCor = cor[1].trim(); //.trim() to remove empty spaces from start and end
.data()
.trim()
Update
For old browser Support use
$.trim() instead of .trim()
var firstCor = $.trim(cor[0]);
var lastCor = $.trim(cor[1]);
or Use String.prototype.trim polyfill
Use .split(), if you want to convert in float use parseFloat
var arr = $('.cor').data('coordinates').split(',');
var firstCor = $.trim(arr[0]);
var lastCor = $.trim(arr[1]);
var co = $('.cor').data('coordinates');
var temp=new Array();
temp=co.split(",");
var firstCor =temp[0];
var lastCor = temp[1];
Another way is to use a regular expression
var cords = $('.cor').data('coordinates').match(/-?\d+\.\d+/g);
which results in array with two strings
["37.650621", "55.740887"]
If you want to convert them to numbers and the browser supports Array map()
var cords = $('.cor')
.data('coordinates')
.match(/-?\d+\.\d+/g)
.map( function(a){ return parseFloat(a); });
which results in
[37.650621, 55.740887]

In JavaScript, How to extract latitude and longitude from string

I am extracting a string from a database which needs to be parsed into latitude and longitude separately,
The string is defined as a "point", in the following format:
(2.340000000,-4.50000000)
I am trying to remove the parenthesis, and then parsed them with the method split() but I haven't been able to come up with a regular expressions that does the job right:
So far I have tried many alternatives, and
var latlong = "(2.34000000, -4.500000000)"
latlong.replace('/[\(\)]//g','');
var coords = latlong.split(',');
var lat = coords[0];
var long = coords[1];
If I run that, all I got is:
NaN, -4.500000
What am I doing wrong?
Thanks!
Seems to work, but you had an extra slash
var value = '(2.340000000,-4.50000000)';
//you had an extra slash here
// ''''''''''''''''v
value = value.replace(/[\(\)]/g,'').split(',');
console.log(value[0]);
console.log(value[1]);​
You can cut out the split and just use the match function with the regex \((\-?\d+\.\d+), (\-?\d+\.\d+)\) which will return the two coordinates. Firebug console output:
>>> "(2.34000000, -4.500000000)".match(/\((\-?\d+\.\d+), (\-?\d+\.\d+)\)/);
["(2.34000000, -4.500000000)", "2.34000000", "-4.500000000"]
var latlong = "(2.34000000, -4.500000000)"
var coords = latlong.replace(/[\(\) ]/g,'').split(',');
console.log(coords[0])
console.log(coords[1])
You can try to use match function:
var latlong = "(2.34000000, -4.500000000)"
var coords = latlong.match(/\((-?[0-9\.]+), (-?[0-9\.]+)\)/);
var lat = coords[1];
var long = coords[2];
alert('lat: ' + lat);
alert('long: ' + long);

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