How to manipulate string [duplicate] - javascript

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]

Related

SubString in JavaScript [duplicate]

This question already has answers here:
How to get the nth occurrence in a string?
(14 answers)
Closed 2 years ago.
For example, I have a string like following
var string = "test1;test2;test3;test4;test5";
I want the following substring from the above string, I don't know the startIndex, the only thing I can tell substring should start after the second semicolon to till the end.
var substring = "test3;test4;test5";
Now I want to have substring like following
var substring2 = "test4;test5"
How to achieve this in JavaScript
You mean this?
const string = "test1;test2;test3;test4;test5";
const arr = string.split(";")
console.log(arr.slice(2).join(";")); // from item #2
console.log(arr.slice(-2).join(";")) // last 2 items
If the string is very long, you may want to use one of these versions
How to get the nth occurrence in a string?
As a function
const string = "test1;test2;test3;test4;test5";
const restOfString = (string,pos) => {
const arr = string.split(";")
return arr.slice(pos).join(";"); // from item #pos
};
console.log(restOfString(string,2))
console.log(restOfString(string,3))
Try to use a combination of string split and join to achieve this.
var s = "test1;test2;test3;test4;test5";
var a = s.split(";")
console.log(a.slice(3).join(";"))

How to remove single quote from comma seprated integer values [duplicate]

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]

How to convert object array to comma separated string? [duplicate]

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;
}, ''));

How can I extract only the integer from a String JavaScript [duplicate]

This question already has answers here:
How to find a number in a string using JavaScript?
(9 answers)
Closed 6 years ago.
I have a string that looks like:
var a = "value is 10 ";
How would I extract just the integer 10 and put it in another variable?
You could use a regex:
var val = +("value is 10".replace(/\D/g, ""));
\D matches everything that's not a digit.
you can use regexp
var a = "value is 10 ";
var num = a.match(/\d+/)[0] // "10"
console.log ( num ) ;
You can use some string matching to get an array of all found digits, then join them together to make the number as a string and just parse that string.
parseInt(a.match(/\d/g).join(''))
However, if you have a string like 'Your 2 value is 10' it will return 210.
You do it using regex like that
const pattern = /\d+/g;
const result = yourString.match(pattern);

How do I split a string with multiple commas and colons in javascript? [duplicate]

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.

Categories

Resources