This question already has answers here:
Splitting a string into chunks by numeric or alpha character with JavaScript
(3 answers)
Closed 4 years ago.
I am not good at regex patterns, I can get everything inside the curly parenthesis with {(.*?)} but I cannot split them.
Suppose I have a string like this
{y12.13bb15.16}
How do I capture it like this into an array:
['y', '12.13', 'bb', '15.16']
although in the end essentially I wanna create an object like this:
{"y": 12.13, "bb": 15.16}
You may use ([\d\.]+|[^\d{}]+)
var rx = /([\d\.]+|[^\d{}]+)/g
s = '{y12.13bb15.16}'
k = s.match(rx)
console.log(k)
// And now to convert to your desired object
var final = {}
for (i = 0; i < k.length; i += 2) {
final[k[i]] = k[i+1]
}
console.log(final)
Related
This question already has answers here:
Regex to find or extract strings between the "<>" angle brackets
(3 answers)
Find substring between angle brackets using jQuery
(3 answers)
Regex to get string between curly braces
(16 answers)
Regular Expression to get a string between parentheses in Javascript
(10 answers)
Closed 4 months ago.
How can implement a function that returns a list of characters between two characters?
const string = "My name is <<firstname>> and I am <<age>>";
const getVariables = (string) => {
// How do I implement?
}
console.log(getVariables(string)); // ['firstname', 'age']
PS: I realize there are multiple answers on how to do something similar, but all of them only work for getting first instance and not all occurrences.
Assuming this is some kind of templating, you can proceed like this:
let format = (str, vars) =>
str.replace(/<<(\w+)>>/g, (_, w) => vars[w]);
//
const tpl = "My name is <<firstname>> and I am <<age>>";
console.log(
format(tpl, {firstname: 'Bob', age: 33})
)
You could search for string which has the starting pattern and end pattern with look behind and look ahead.
const
string = "My name is <<firstname>> and I am <<age>>",
parts = string.match(/(?<=\<\<).*?(?=\>\>)/g);
console.log(parts);
You could use regex, group, matchAll and get the first group
const string = "My name is <<firstname>>, from <<place>>, and I am <<age>>"
const getVariables = string => {
return [...string.matchAll(/<<(\w+)>>/g)].map(match => match[1])
}
console.log(getVariables(string))
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;
}, ''));
This question already has answers here:
How does adding String with Integer work in JavaScript? [duplicate]
(5 answers)
Closed 4 years ago.
I would like to combine two or more variables into the same array index but not do anything to the values, just place them together in the same array index
So
var myArray[];
var one= 1;
var two = 2;
etc...
myArray.push("one" + "two")
document.write(myArray[0];
Should output 12 or 1 2 but not add them together to show 3.
Remove double quotes and for converting to string just add a '' between them. This kind of converting is more efficience than String()
var myArray = [];
var one = 1;
var two = 2;
myArray.push(one + '' + two)
document.write(myArray[0]);
You can do this, using String to convert the numbers into strings and then + will perform string concatenation instead of numeric addition.
const myArray = [];
const one = 1;
const two = 2;
myArray.push(String(one) + String(two));
console.log(myArray);
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);
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.