slice string into two variables - javascript

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]

Related

Set part of string equal to part of array

I want to set a part of a string equal to part of an array. Basically the following is what I've attempted:
var x=[4,6,9,2];
var y="hello";
// y[0] is h; y[1] is e; and so on
y[0] = x[2];
alert(y);
// should alert 9ello; but it doesn't, any ideas?
Strings are immutable. The array notation can only be used to get characters, but not to set them.
You should split the string into an array of characters, and join it back at the end.
y = y.split(''); // ["h","e","l","l","o"]
y[0] = x[2]; // ["9","e","l","l","o"]
y = y.join(''); // "9ello"
You can use replace and put the results in a new string:
var x=[4,6,9,2];
var y="hello";
var z= y.replace(y[0], x[2]);
alert(z);
Or without creating a new string:
var x=[4,6,9,2];
var y="hello";
alert (y.replace(y[0], x[2]) );

Split text with a single code

var objname = "Image1-123456-789.png"
quick question i wanted to split this text without match them together again.
here is my code
var typename = objname.split("-");
//so it will be Image1,123456,789.png
var SplitNumber = typename[1]+'-'+typename[2];
var fullNumber = SplitCode.split('.')[0];
to get what i wanted
my intention is to get number is there anyway i can split them without join them and split again ?
can a single code do that perfectly ? my code look like so many job.
i need to get the 123456-789.
The String.prototype.substring() method extracts the characters from a string, between two specified indices, and returns the new sub string.
This method extracts the characters in a string between "start" and "end", not including "end" itself.
var objname = "Image1-123456-789.png";
var newname = objname.substring(objname.indexOf("-")+1, objname.indexOf("."));
alert(newname);
An alternate can be using Join. You can use slice to fetch range of values in array and then join them using -.
var objname = "Image1-123456-789.png";
var fullnumber = objname.split("-").slice(1).join("-").split(".")[0];
alert(fullnumber)
Reference
Join Array from startIndex to endIndex
Here is your solution
var objname = "Image1-123456-789.png";
var typename= objname.split("-");
var again=typename[2];
var again_sep= again.split(".");
var fullNumber =typename[1]+'-'+again_sep[0];

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("");

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

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];

Categories

Resources