Split square brackets into commas, remove first and last comma - javascript

I have written the following console log to convert a list of [] to commas:
[Item 1][Item 2][Item 3][Item 4]
...
.split(/[[\]]{1,2}/);
but I am getting the following printed out:
,Item 1,Item 2,Item 3,Item 4,
when I am looking for:
Item 1,Item 2,Item 3,Item 4
I have tried a variety of different approaches but none provide me with the above last result.

You could use match instead of split and take directly the result array.
var string = '[Item 1][Item 2][Item 3][Item 4]',
parts = string.match(/[^\[\]]+/g);
console.log(parts);

Without going with regex, you could just slice it before splitting.
var str = "[Item 1][Item 2][Item 3][Item 4]";
var result = str.slice(1,-1).split`][`;
console.log(result);
The regex option would be:
var str = "[Item 1][Item 2][Item 3][Item 4]";
var result = str.match(/[\w ]+/g);
console.log(result);

Related

Regex giving incorrect results

Working in Javascript attempting to use a regular expression to capture data in a string.
My string appears as this starting with the left bracket
['ABC']['ABC.5']['ABC.5.1']
My goal is to get each piece of the regular expression as a chunk or in array.
I have reviewed and see that the match function might be a good choice.
var myString = "['ABC']['ABC.5']['ABC.5.1']";
myString.match(/\[/g]);
The output I see is only the [ for each element.
I would like the array to be like this for example
myString[0] = ['ABC']
myString[1] = ['ABC.5']
myString[2] = ['ABC.5.1']
What is the correct regular expression and or function to get the above-desired output?
If you just want to separate them, you can use a simple expression or better than that you can split them:
\[\'(.+?)'\]
const regex = /\[\'(.+?)'\]/gm;
const str = `['ABC']['ABC.5']['ABC.5.1']`;
const subst = `['$1']\n`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
DEMO
You can use this regex with split:
\[[^\]]+
Details
\[ - Matches [
[^\]]+ - Matches anything except ] one or more time
\] - Matches ]
let str = `['ABC']['ABC.5']['ABC.5.1']`
let op = str.split(/(\[[^\]]+\])/).filter(Boolean)
console.log(op)

Regex for matching only first of two same characters in a string

I have these two strings: "1-2" and "1--2".
I would like to have a regex that would match only the first occurrence of the hyphen in both strings, such that the split would then be: [1,2] and [1,-2]. How would I achieve this, since I have been wracking my brain for too long on this now?
EDIT: The two strings can also occur in the same string such that: "1-2-1--2". Therefore a single regular expression covering both cases would be in order.
You can use this split with a word boundary before -:
let s='1-2-1--2'
let arr = s.split(/\b-/)
console.log(arr)
//=> [1, 2, 1, -2)
You can use simple split(), but with replacement. For example,
var str = '1-2-1--2';
var numArr = str.replace(/--/g, '-~') // The tilde (~) have no mean, this is a charceter for mark a negative number
.split('-')
.map(function(n) { return Number(n.replace('~', '-')); });
console.log(numArr);
I think you're looking for something like this:
(-?[0-9]+)-(-?[0-9]+)
where the first and the second group could have a negative sign
UPDATE:
based on your edit, this implementation would do the job:
var str = '-1--2-2--34-1';
var regex = /(-?\d+)-?/g;
var matches = [];
while((match = regex.exec(str))) {
matches.push(match[1]);
}
console.log(matches);
I prefer using split, but it's fine if you only want to use RegEx.

String to array node js javascript

Hi my current string is shown:
082759
078982
074470
066839
062069
062068
062029
062027
059304
059299
056449
056421
052458
050666
100530
078977
072967
072958
072957
066982
062864
062064
056506
052456
24 6 digit numbers in total, notice the new lines between them.
I need this entire string to be broken down into an array such that [082759,078982,etc] is displayed and so that when calling:
console.log(array[0])
will output:
082759
NOTE: The '\n' method does not seem to work and when re-calling it [when within an array], e.g array[0], it outputs all the numbers.
The variable under which this data is derived from comes via:
var currentSku = $(this).attr('data-productsku')
So if this j-query has a specific string type then its probably something to do with this?
Because they have '\n' in-between, use split()
let arr = str.split('\n')
console.log(arr[0]);
If you're adding the digit on a new-line each time, you can use .split() method.
You have to pass the delimiter you want to split by; in your case, you use \n as that's how new-lines are escaped in Javascript. This will create an array of data.
Using the code below you can do like so:
let string = `082759
078982
074470
066839
062069
062068
062029
062027
059304
059299
056449
056421
052458
050666
100530
078977
072967
072958
072957
066982
062864
062064
056506
052456`;
let arr = string.split('\n');
console.log(arr[0]);
Try this code
var test = "082759 078982 074470 066839 062069 062068";
var arr = test.split(" ");
console.log(arr[0]);
console.log(arr[4]);
Tested code!
Note: There should be a space in between each number.
Next line solution is here
var test =
`082759
078982
074470
066839
062069
06206`;
var arr = test.split("\n");
console.log(arr[0]);
console.log(arr[4]);
If splitting using \n doesn't work then it might be that your string is using a different style of line ending. You can try \r or \r\n for instance.
array.split(/\n/)
or
array.split(\n)

How can I capture word by Regex

I would like to capture the array key from a string.
Here are my words: message[0][generic][0][elements][0][default_action][url]...
I want to capture the array keys after message[0][generic][0][elements][0], and the expected results are default_action and url etc.
I have tried following patterns but not work.
message\[0\]\[generic\]\[0\]\[elements\]\[0\](?=\[(\w+)\]): it captures default_action only;
\[(\w+)\]: it captures all array keys, but includes 0, generic, elements...
Is there any regex pattern for JavaScript that make the result array inverse, like [url, default_action]?
You can replace unwanted part of a string,and then get all other keys.
var string = 'message[0][generic][0][elements][0][default_action][url][imthird]';
var regexp = /message\[0\]\[generic\]\[0\]\[elements\]\[0\]/
var answer = string.replace(regexp,'').match(/[^\[\]]+/g)
console.log(answer);
To extract any number of keys and reverse the order of the elements in resulting array:
str = "message[0][generic][0][elements][0][default_action][url]";
res = str.match(/\[([^\d\]]+)\](?=\[[^\d\]]*\]|$)/g)
.map(function(s) { return s.replace(/[\[\]]/g, "") })
.reverse();
console.log(res);
The solution using String.prototype.split() and Array.prototype.slice() functions:
var s = 'message[0][generic][0][elements][0][default_action][url]...',
result = s.split(/\]\[|[\[\]]/g).slice(-3,-1);
console.log(result);

split an array string (split is not working) in javascript

I have an array like ["one, two, three"].
I want to convert it to ["one","two","three"].
I was using split to do this like:
$var temp=["one, two, three"];
temp.split(", ");
This is giving me error. Any idea how to do this?
It's an array with one single value, and you'd access that with [0] to get the string
var temp = ["one, two, three"];
var arr = temp[0].split(", ");
seems easier to just drop the brackets
var arr = "one, two, three".split(', ');
or write it as an array to begin with ?
["one, two, three"].pop().split(", ")
var temp=["one, two, three"];
temp[0].split(", ")

Categories