Set part of string equal to part of array - javascript

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

Related

How to get the string value after the colon?

I really need your help,
How can I check a string to see if it has a ":" and then if it does, to get the string value after the ":"
ie.
var x = "1. Search - File Number: XAL-2017-463288"
var y = "XAL-2017-463288"
//check for the colon
if (x.indexOf(':') !== -1) {
//split and get
var y = x.split(':')[1];
}
Split on the colon, and grab the second member of the result. This assumes you want the first colon found.
var y = x.split(":")[1];
If the string didn't have a :, then y will be undefined, so a separate check isn't needed.
Or you could use .indexOf(). This assumes there's definitely a colon. Otherwise you'll get the whole string.
var y = x.slice(x.indexOf(":") + 1);
If you wanted to check for the colon, then save the result of .indexOf() to a variable first, and only do the .slice() if the index was not -1.

How to get ASCII of number in JavaScript?

I am aware of name.charCodeAt(0). I am having issued with the following code, so I want a solution for below.
var number= 2;
var t = number.charCodeAt(0);
console.log(t);
The answer needs to be in ASCII. I am getting the log as 2 and not as ASCII value 50. What can be the issue?
ASCII is a way of representing String data. You need to first convert your Number to String;
Remember also that String can have arbitrary length so you'll need to iterate over every character.
var x = 2,
str_x = '' + x,
chrs = Array.prototype.map.call(str_x, function (e) {return e.charCodeAt(0);});
chrs; // [50]
Finally, JavaScript works with UTF-16/UCS-2 and not plain ASCII. Luckily the values for digits are the same in both so you don't have to do any further transformation here.
You have to cast a number to a string first to use .charCodeAt to get the numerical character code.
var number = 2;
var t = String( number ).charCodeAt( 0 );
console.log( t ); // 50
Just convert the number to String and call the method on it.
var number = 2;
var numberInString = number.toString();
var code = numberInString.charCodeAt(0);
console.log(code);

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

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]

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