JS split, keep delimiter minus its first character - javascript

Original, string: "FOO,blue,FOO,yellow,red,FOO,purple,brown,blue,FOOred,orange,FOO,blue,yellow"
I'd like to convert this mixed string to an array, splitting specifically at each ,FOO, and keep FOO.
Code:
var str = "blue,FOO,yellow,red,FOO,purple,brown,blue,FOOred,orange,FOO,blue,yellow"
var regex = /(?=,FOO)/g
console.log(str.split(regex))
Codepen
Desired result:
[
'FOO,blue',
'FOO,yellow,red',
'FOO,purple,brown,blue',
'FOOred,orange',
'FOO,blue,yellow',
]
Current result:
[
'FOO,blue',
',FOO,yellow,red',
',FOO,purple,brown,blue',
',FOOred,orange',
',FOO,blue,yellow',
]
As you see, each FOO instance included the preceding comma; how can I exclude the comma in the same regex operation?
var str = "FOO,blue,FOO,yellow,red,FOO,purple,brown,blue,FOOred,orange,FOO,blue,yellow"
var regex = /(?=,FOO)/g
console.log(str.split(regex))

You're only looking ahead for the comma at the moment - you need to include it in the match (outside of the lookahead) for it to be split upon and not included in the result.
var str = "FOO,blue,FOO,yellow,red,FOO,purple,brown,blue,FOOred,orange,FOO,blue,yellow"
var regex = /,(?=FOO)/g
console.log(str.split(regex))

Related

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);

Split string and get array using regExp in javascript/node js

I am writing js code to get array of elements after splitting using regular expression.
var data = "ABCXYZ88";
var regexp = "([A-Z]{3})([A-Z]{3}d{2})";
console.log(data.split(regexp));
It returns
[ 'ABCXYZ88' ]
But I am expecting something like
['ABC','XYZ','88']
Any thoughts?
I fixed your regex, then matched it against your string and extracted the relevant capturing groups:
var regex = /([A-Z]{3})([A-Z]{3})(\d{2})/g;
var str = 'ABCXYZ88';
let m = regex.exec(str);
if (m !== null) {
console.log(m.slice(1)); // prints ["ABC", "XYZ", "88"]
}
In your case, I don't think you can split using a regex as you were trying, as there don't seem to be any delimiting characters to match against. For this to work, you'd have to have a string like 'ABC|XYZ|88'; then you could do 'ABC|XYZ|88'.split(/\|/g). (Of course, you wouldn't use a regex for such a simple case.)
Your regexp is not a RegExp object but a string.
Your capturing groups are not correct.
String.prototype.split() is not the function you need. What split() does:
var myString = 'Hello World. How are you doing?';
var splits = myString.split(' ', 3);
console.log(splits); // ["Hello", "World.", "How"]
What you need:
var data = 'ABCXYZ88';
var regexp = /^([A-Z]{3})([A-Z]{3})(\d{2})$/;
var match = data.match(regexp);
console.log(match.slice(1)); // ["ABC", "XYZ", "88"]
Try this. I hope this is what you are looking for.
var reg = data.match(/^([A-Z]{3})([A-Z]{3})(\d{2})$/).slice(1);
https://jsfiddle.net/m5pgpkje/1/

Get all characters except hyphen and brackets from string using javascript regex

I have a string like this:
var myString = "MyString-[ADDAAD]-isGreat";
I want to extract this string into 3 parts:
var stringOne = "MyString-";
var stringTwo = "ADDAAD";
var stringThree = "-isGreat";
I know how to get the string between the two square brackets:
var matches = patternString.match(/\[(.*?)\]/);
now matches[1] contains ADDAAD
But how can I get the other two parts?
Select every character except -, [ and ] using bottom regex.
var myString = "MyString-[ADDAAD]-isGreat";
var parts = myString.match(/[^-\[\]]+/g);
console.log(parts);
So if you want to store values in custom variable, use bottom code
var stringOne = parts[0];
var stringTwo = parts[1];
var stringThree = parts[2];
You may split the string with your regex. Note that all the capturing group contents will be also part of the resulting array. To avoid empty items, you may add .filter(Boolean) after split().
See a JS demo below:
var myString = "MyString-[ADDAAD]-isGreat";
console.log(myString.split(/\[(.*?)]/).filter(Boolean));
console.log("s1-[s2]".split(/\[(.*?)]/).filter(Boolean));
Note you do not have to escape a ] used outside character classes, it is always parsed as a literal closing bracket if there is no corresponding [ before it.

JS - Split string into substrings by regex

Let's say I have a string that starts by 7878 and ends by 0d0a or 0D0A such as:
var string = "78780d0101234567890123450016efe20d0a";
var string2 = "78780d0101234567890123450016efe20d0a78780d0103588990504943870016efe20d0a";
var string 3 = "78780d0101234567890123450016efe20d0a78780d0103588990504943870016efe20d0a78780d0101234567890123450016efe20d0a"
How can I split it by regex so it becomes an array like:
['78780d0101234567890123450016efe20d0a']
['78780d0101234567890123450016efe20d0a','78780d0101234567890123450016efe20d0a']
['78780d0101234567890123450016efe20d0a','78780d0101234567890123450016efe20d0a','78780d0101234567890123450016efe20d0a']
You can split the string with a positive lookahead (?=7878). The regex isn't consuming any characters, so 7878 will be part of the string.
var rgx = /(?=7878)/;
console.log(string1.split(rgx));
console.log(string2.split(rgx));
console.log(string3.split(rgx));
Another option is to split on '7878' and then take all the elements except first and add '7878' to each of them. For example:
var arr = string3.split('7878').slice(1).map(function(str){
return '7878' + str;
});
That works BUT it also matches strings that do NOT end on 0d0a. How
can I only matches those ending on 0d0a OR 0D0A?
Well, then you can use String.match with a plain regex.
console.log(string3.match(/7878.*?0d0a/ig));

How to extract two strings from url using regex?

I've matched a string successfully, but I need to split it and add some new segments to URL. If it is possible by regex, How to match url and extract two strings like in the example below?
Current result:
["domain.com/collection/430000000000000"]
Desired result:
["domain.com/collection/", "430000000000000"]
Current code:
var reg = new RegExp('domain.com\/collection\/[0-9]+');
var str = 'http://localhost:3000/#/domain.com/collection/430000000000000?page=0&layout=grid';
console.log(str.match(reg));
You want Regex Capture Groups.
Put the parts you want to extract into braces like this, each part forming a matching group:
new RegExp('(domain.com\/collection\/)([0-9]+)')
Then after matching, you can extract each group content by index, with index 0 being the whole string match, 1 the first group, 2 the second etc. (thanks for the addendum, jcubic!).
This is done with exec() on the regex string like described here:
/\d(\d)\d/.exec("123");
// → ["123", "2"]
First comes the whole match, then the group matches in the sequence they appear in the pattern.
You can declare an array and then fill it with the required values that you can capture with parentheses (thus, making use of capturing groups):
var reg = /(domain.com\/collection)\/([0-9]+)/g;
// ^ ^ ^ ^
var str = 'http://localhost:3000/#/domain.com/collection/430000000000000?page=0&layout=grid';
var arr = [];
while ((m = reg.exec(str)) !== null) {
arr.push(m[1]);
arr.push(m[2]);
}
console.log(arr);
Output: ["domain.com/collection", "430000000000000"]

Categories

Resources