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

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.

Related

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]

Extract strings between occurences of a specific character

I'm attempting to extract strings between occurences of a specific character in a larger string.
For example:
The initial string is:
var str = "http://www.google.com?hello?kitty?test";
I want to be able to store all of the substrings between the question marks as their own variables, such as "hello", "kitty" and "test".
How would I target substrings between different indexes of a specific character using either JavaScript or Regular Expressions?
You could split on ? and use slice passing 1 as the parameter value.
That would give you an array with your values. If you want to create separate variables you could for example get the value by its index var1 = parts[0]
var str = "http://www.google.com?hello?kitty?test";
var parts = str.split('?').slice(1);
console.log(parts);
var var1 = parts[0],
var2 = parts[1],
var3 = parts[2];
console.log(var1);
console.log(var2);
console.log(var3);
Quick note: that URL would be invalid. A question mark ? denotes the beginning of a query string and key/value pairs are generally provided in the form key=value and delimited with an ampersand &.
That being said, if this isn't a problem then why not split on the question mark to obtain an array of values?
var split_values = str.split('?');
//result: [ 'http://www.google.com', 'hello', 'kitty', 'test' ]
Then you could simply grab the individual values from the array, skipping the first element.
I believe this will do it:
var components = "http://www.google.com?hello?kitty?test".split("?");
components.slice(1-components.length) // Returns: [ "hello", "kitty", "test" ]
using Regular Expressions
var reg = /\?([^\?]+)/g;
var s = "http://www.google.com?hello?kitty?test";
var results = null;
while( results = reg.exec(s) ){
console.log(results[1]);
}
The general case is to use RegExp:
var regex1 = new RegExp(/\?.*?(?=\?|$)/,'g'); regex1.lastIndex=0;
str.match(regex1)
Note that this will also get you the leading ? in each clause (no look-behind regexp in Javascript).
Alternatively you can use the sticky flag and run it in a loop:
var regex1 = new RegExp(/.*?\?(.*?)(?=\?|$)/,'y'); regex1.lastIndex=0;
while(str.match(regex1)) {...}
You can take the substring starting from the first question mark, then split by question mark
const str = "http://www.google.com?hello?kitty?test";
const matches = str.substring(str.indexOf('?') + 1).split(/\?/g);
console.log(matches);

how can i replace first two characters of a string in javascript?

lets suppose i have string
var string = "$-20455.00"
I am trying to swap first two characters of a string. I was thinking to split it and make an array and then replacing it, but is there any other way? Also, I am not clear how can I achieve it using arrays? if I have to use arrays.
var string = "-$20455.00"
How can I achieve this?
You can use the replace function in Javascript.
var string = "$-20455.00"
string = string.replace(/^.{2}/g, 'rr');
Here is jsfiddle: https://jsfiddle.net/aoytdh7m/33/
You dont have to use arrays. Just do this
string[1] + string[0] + string.slice(2)
You can split to an array, and then reverse the first two characters and join the pieces together again
var string = "$-20455.00";
var arr = string.split('');
var result = arr.slice(0,2).reverse().concat(arr.slice(2)).join('');
document.body.innerHTML = result;
try using the "slice" method and string concatenation:
stringpart1 = '' //fill in whatever you want to replace the first two characters of the first string with here
string2 = stringpart1 + string.slice(1)
edit: I now see what you meant by "swap". I thought you meant "swap in something else". Vlad's answer is best to just switch the first and the second character.
Note that string[0] refers to the first character in the string, and string[1] to the second character, and so on, because code starts counting at 0.
var string = "$-20455.00";
// Reverse first two characters
var reverse = string.slice(0,2).split('').reverse().join('');
// Concat again with renaming string
var result= reverse.concat(string.slice(2));
document.body.innerHTML = result;
let finalStr = string[1] + string[0] + string.slice(2); //this will give you the result

RegEx for filling up string

I have the following input:
123456_r.xyz
12345_32423_131.xyz
1235.xyz
237213_21_mmm.xyz
And now I need to fill up the first connected numbers to 8 numbers leading with 0:
00123456_r.xyz
00012345_32423_131.xyz
00001235.xyz
00237213_21_mmm.xyz
My try was to split a the dot, then split (if existing) at the underscore and get the first numbers and fill them up.
But I think there will be a more efficient way with the regex replace function with just the one function, right? How would this look like?
TIA
Matt
I would use a regex, but just for the spliting :
var input = "12345_32423_131.xyz";
var output = "00000000".slice(input.split(/_|\./)[0].length)+input;
Result : "00012345_32423_131.xyz"
EDIT :
the fast, no-splitting but no-regex, solution I gave in comments :
"00000000".slice(Math.min(input.indexOf('_'), input.indexOf('.'))+1)+input
I wouldn't split at all, just replace:
"123456_r.xyz\n12345_32423_131.xyz\n1235.xyz\n237213_21_mmm.xyz".replace(/^[0-9]+/mg, function(a) {return '00000000'.slice(0, 8-a.length)+a})
There's a simple regexp to find the part of the string you want to replace, but you'll need to use a replace function to perform the action you want.
// The array with your strings
var strings = [
'123456_r.xyz',
'12345_32423_131.xyz',
'1235.xyz',
'237213_21_mmm.xyz'
];
// A function that takes a string and a desired length
function addLeadingZeros(string, desiredLength){
// ...and, while the length of the string is less than desired..
while(string.length < desiredLength){
// ...replaces is it with '0' plus itself
string = '0' + string;
}
// And returns that string
return string;
}
// So for each items in 'strings'...
for(var i = 0; i < strings.length; ++i){
// ...replace any instance of the regex (1 or more (+) integers (\d) at the start (^))...
strings[i] = strings[i].replace(/^\d+/, function replace(capturedIntegers){
// ...with the function defined above, specifying 8 as our desired length.
return addLeadingZeros(capturedIntegers, 8);
});
};
// Output to screen!
document.write(JSON.toString(strings));

How to remove the last matched regex pattern in javascript

I have a text which goes like this...
var string = '~a=123~b=234~c=345~b=456'
I need to extract the string such that it splits into
['~a=123~b=234~c=345','']
That is, I need to split the string with /b=.*/ pattern but it should match the last found pattern. How to achieve this using RegEx?
Note: The numbers present after the equal is randomly generated.
Edit:
The above one was just an example. I did not make the question clear I guess.
Generalized String being...
<word1>=<random_alphanumeric_word>~<word2>=<random_alphanumeric_word>..~..~..<word2>=<random_alphanumeric_word>
All have random length and all wordi are alphabets, the whole string length is not fixed. the only text known would be <word2>. Hence I needed RegEx for it and pattern being /<word2>=.*/
This doesn't sound like a job for regexen considering that you want to extract a specific piece. Instead, you can just use lastIndexOf to split the string in two:
var lio = str.lastIndexOf('b=');
var arr = [];
var arr[0] = str.substr(0, lio);
var arr[1] = str.substr(lio);
http://jsfiddle.net/NJn6j/
I don't think I'd personally use a regex for this type of problem, but you can extract the last option pair with a regex like this:
var str = '~a=123~b=234~c=345~b=456';
var matches = str.match(/^(.*)~([^=]+=[^=]+)$/);
// matches[1] = "~a=123~b=234~c=345"
// matches[2] = "b=456"
Demo: http://jsfiddle.net/jfriend00/SGMRC/
Assuming the format is (~, alphanumeric name, =, and numbers) repeated arbitrary number of times. The most important assumption here is that ~ appear once for each name-value pair, and it doesn't appear in the name.
You can remove the last token by a simple replacement:
str.replace(/(.*)~.*/, '$1')
This works by using the greedy property of * to force it to match the last ~ in the input.
This can also be achieved with lastIndexOf, since you only need to know the index of the last ~:
str.substring(0, (str.lastIndexOf('~') + 1 || str.length() + 1) - 1)
(Well, I don't know if the code above is good JS or not... I would rather write in a few lines. The above is just for showing one-liner solution).
A RegExp that will give a result that you may could use is:
string.match(/[a-z]*?=(.*?((?=~)|$))/gi);
// ["a=123", "b=234", "c=345", "b=456"]
But in your case the simplest solution is to split the string before extract the content:
var results = string.split('~'); // ["", "a=123", "b=234", "c=345", "b=456"]
Now will be easy to extract the key and result to add to an object:
var myObj = {};
results.forEach(function (item) {
if(item) {
var r = item.split('=');
if (!myObj[r[0]]) {
myObj[r[0]] = [r[1]];
} else {
myObj[r[0]].push(r[1]);
}
}
});
console.log(myObj);
Object:
a: ["123"]
b: ["234", "456"]
c: ["345"]
(?=.*(~b=[^~]*))\1
will get it done in one match, but if there are duplicate entries it will go to the first. Performance also isn't great and if you string.replace it will destroy all duplicates. It would pass your example, but against '~a=123~b=234~c=345~b=234' it would go to the first 'b=234'.
.*(~b=[^~]*)
will run a lot faster, but it requires another step because the match comes out in a group:
var re = /.*(~b=[^~]*)/.exec(string);
var result = re[1]; //~b=234
var array = string.split(re[1]);
This method will also have the with exact duplicates. Another option is:
var regex = /.*(~b=[^~]*)/g;
var re = regex.exec(string);
var result = re[1];
// if you want an array from either side of the string:
var array = [string.slice(0, regex.lastIndex - re[1].length - 1), string.slice(regex.lastIndex, string.length)];
This actually finds the exact location of the last match and removes it regex.lastIndex - re[1].length - 1 is my guess for the index to remove the ellipsis from the leading side, but I didn't test it so it might be off by 1.

Categories

Resources