This question already has answers here:
Transform Javascript Array into delimited String
(7 answers)
Closed 4 years ago.
Im trying to convert at object array with jQuery or javascript to a comma separated string, and no matter what I try I canĀ“t get it right.
I have this from a select value.
ort = $('#ort').val();
ort=JSON.stringify(ort)
ort=["Varberg","Halmstad","Falkenberg"]
How can I convert it to a string looking like this?
ort=Varberg,Halmstad,Falkenberg
Any input appreciated, thanks.
You can use join
let arr = ["Varberg","Halmstad","Falkenberg"]
console.log(arr.join(','))
Use Array.prototype.join to to convert it into a comma separated string.
let str = ort=["Varberg","Halmstad","Falkenberg"].join(","); //"," not needed in join
console.log(str);
A simple toString also works in this case.
let str = ort=["Varberg","Halmstad","Falkenberg"].toString();
console.log(str);
Another way to achieve this is by using Array.prototype.reduce:
console.log(["Varberg", "Halmstad", "Falkenberg"].reduce((s, el, idx, arr) => {
s += el
if (idx < arr.length - 1) {
s += ','
}
return s;
}, ''));
Related
This question already has answers here:
Split string and get first value only
(4 answers)
Closed 4 months ago.
I have a DateTime string like below:
"11/20/2022 19.00"
I just want to delete the spaces until the end, how do I do that?
I'm expecting the below output:
"11/20/2022"
If space comes break the string
let str = "11/20/2022 19.00"
let ans="";
for(let i=0 ; i<str.length ; i++){
if(str[i]!==" "){
ans+=str[i];
}
else{
break ;
}
}
console.log((ans));
If your date string follows the standard format
Try to use String.prototype.slice() and pass the beginning and end of the slice portion as the first and second params.
const dateTime = "11/20/2022 19.00"
console.log(dateTime.slice(0, 10))
If your date string did not follow the standard format
You can first split it by space (String.prototype.split()) and then use the first part of the output array generated by the split function.
const dateTime = "1/2/2022 19.00"
console.log(dateTime.split(" ")[0])
You can simply use split function of javascript
You can use split function of javascript to split the string and then take first index as you required result.
let a = "11/20/2022 19.00";
let reqFormat = a.split(' ')[0]
This question already has answers here:
What is the shortest function for reading a cookie by name in JavaScript?
(20 answers)
Closed 2 years ago.
I have this string
"G_ENABLED_IDPS=app; COOKIE_EINF=someCookie; _ga=someGA;
_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5"
And i need some sort of function to split this string given an argument , for example given that my string is text
text.split(";") , will split it into an array separating it by ";"
But i need a function like this
returnText(text , property) that would work like
returnText(text, "_gcl_au") --> returns "someglcau"
You could actually use a regex replacement approach here, for a one-liner option:
function returnText(text, property) {
var term = text.replace(new RegExp("^.*\\b" + property + "=([^;]+)\\b.*$", "gm"), "$1");
return term;
}
var input = "G_ENABLED_IDPS=app; COOKIE_EINF=someCookie;_ga=someGA;_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5";
console.log(returnText(input, "_gcl_au"));
you can use split, just as you tried:
function returnText(text , property){
entries = text.split('; ');
const newEntries = [];
entries.forEach(item => {
let vals = item.split('=');
newEntries[vals[0]] = vals[1]
});
return newEntries[property];
}
const text = "G_ENABLED_IDPS=app; COOKIE_EINF=someCookie; _ga=someGA;_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5";
console.log(returnText(text,'_gcl_au'));
This question already has answers here:
How to convert a string of numbers to an array of numbers?
(18 answers)
Closed 3 years ago.
I m getting result as '2,3,7' as result from database, now I want to remove ' (single quote) from the string and get output as 2,3,7
My intention is to use this values as array like [2,3,7]. But due to it is string it is storing like ['2,3,7'].
I have tried to convert it to an integer using parseInt but it is giving me first index value i.e 2 in this case.
So basically input is like '2,3,7' and expected output is like 2,3,7.
Updation :
I can see many peoples are considering input as "'2,3,7'", consider input as '2,3,7'.
Also I have one working solution for this :
var str = '2,3,7',finalOutput=[];
var splittedValues = str.split(",");
splittedValues.forEach((value) => {
finalOutput.push(parseInt(value));
});
Is there any direct way to do this.
Thanks in advance.
Using Regex match()
DEMO: https://regex101.com/r/JhTkVB/1
var string1 = "'2,3,7'"
var string2 = "2,3,7"
console.log(string1.match(/\d+/g).map(Number));
console.log(string2.match(/\d+/g).map(Number));
The easiest way to do what you want is the following:
let str = '2, 3, 7';
let yourArray = str.split(',').map(Number);
console.log(yourArray);
This splits by the comma and then uses the map function which converts each value in an array using the function given as argument and stores them in a new array. So in this case, the function Number is called thrice with the arguments '2', '3' and '7'. Number is the constructor of the number object which also parses string to a number. The resulting array is then stored in yourArray which then has the value [2, 3, 7].
You could remove first and last characters.
var string = "'2,3,7'",
values = string.slice(1, -1);
console.log(values);
Here is another way to remove the enclosing single quotes -
var str = "'2,3,7'",
str = str.substring(1, str.length - 1)
console.log(str);
//If you need an array then
str = str.split(',').map(Number)
console.log(str);
As per your update, it seems as though your input string is simply '2,3,7'. To convert this into an array of numbers, you can use JSON.parse() by encapsulating your string in square brackets like so:
const str = '2,3,7';
const arr = JSON.parse(`[${str}]`);
console.log(arr); // [2, 3, 7]
This question already has answers here:
Converting any string into camel case
(44 answers)
Closed 8 years ago.
I've seen plenty of easy ways to convert camelCaseNames to camel Case Names, etc. but none on how to convert Sentence case names to sentenceCaseNames. Is there any easy way to do this in JS?
This should do the trick :
function toCamelCase(sentenceCase) {
var out = "";
sentenceCase.split(" ").forEach(function (el, idx) {
var add = el.toLowerCase();
out += (idx === 0 ? add : add[0].toUpperCase() + add.slice(1));
});
return out;
}
Explanation:
sentenceCase.split(" ") creates and array out of the sentence eg. ["Sentence", "case", "names"]
forEach loops through each variable in the array
inside the loop each string is lowercased, then the first letter is uppercased(apart for the first string) and the new string is appended to the out variable which is what the function will eventually return as the result.
This question already has answers here:
How do I split a string with multiple separators in JavaScript?
(25 answers)
Closed 8 years ago.
How do I split a string with multiple separators in JavaScript? I'm trying to split on both commas and : colon but, js's split function only supports one separator.
Example :
materialA:125,materialB:150,materialC:175
I want to split both these values into array like
materiaA,materialB,materialC
and second
125,150,175
Or anybody can give me idea how could I multiply these numbers with a constant to get like
materialA:1250, materialB:1500,materialC:1750.
You can split with more than one seperator if you're using regex:
.split(/:|,/)
This would give
["materialA", "125", "materialB", "150", "materialC", "175"]
Changing the approach completely, if all you want to do is multiply all the numbers in your string by a fixed coefficient, you can use string.replace:
var string = "materialA:125,materialB:150,materialC:175";
var coef = 10;
var result = string.replace(/\d+/g, function(match){
return parseInt(match)*coef;
});
Then print(result) outputs the string
materialA:1250,materialB:1500,materialC:1750
\d is a shortcut for [0-9].
Example using #mitim's method:
var str = 'materialA:125,materialB:150,materialC:175',
multiplier = 2;
str = str.split(',').map(function (elem) {
var parts = elem.split(':');
parts[1] *= multiplier;
return parts.join(':');
}).join(',');
This will give you:
materialA:250,materialB:300,materialC:350
You could split the string by comma first, then loop through the resulting array. In that array, each entry would be something like "materialA:125". From there, you can split by the colon and append each part to its own list to work with or if you prefer, just multiply the second half (cast to int first) and rejoin it in to your original string.
Even though someone gave a much better answer, here's a bit of code that does what I mentioned above (since you asked)
var inputString = "materialA:125,materialB:150,materialC:175";
var mats = new Array();
var numbers = new Array();
var temp;
var elements = inputString.split(",");
for(var element in elements){
temp = elements[element].split(":");
mats.push(temp[0]);
numbers.push(parseInt(temp[1]));
}
console.log(mats); // prints ["materialA", "materialB", "materialC"]
console.log(numbers); // prints [125, 150, 175]
You could simply use following Regex:
/[:,]/
And following string method:
mystring = 'materialA:125,materialB:150,materialC:175';
result = mystring.split(/[:,]/);
Here is a Fiddle.