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

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/

Related

JavaScript Split with RegEx without Global Match

I have an expression.
var expression = "Q101='You will have an answer here like a string for instance.'"
I have a regular expression that searches the expression.
var regEx = new regExp(/=|<>|like/)
I want to split the expression using the regular expression.
var result = expression.split(regExp)
This will return the following:
["Q101", "'You will have an answer here ", " a string for instance'"]
This is not what I want.
I should have:
["Q101", "'You will have an answer here like a string for instance'"]
How do I use the regular expression above to split only on the first match?
Since you only want to grab the two parts either side of the first delimiter it might be easier to use String.match and discard the whole match:
var expression = "Q101='You will have an answer here like a string for instance.'";
var parts = expression.match(/^(.*?)(?:=|<>|like)(.*)$/);
parts.shift();
console.log(parts);
expression = "Q101like'This answer uses like twice'";
parts = expression.match(/^(.*?)(?:=|<>|like)(.*)$/);
parts.shift();
console.log(parts);
JavaScript's split method won't quite do what you want, because it will either split on all matches, or stop after N matches. You need an extra step to find the first match, then split once by the first match using a custom function:
function splitMatch(string, match) {
var splitString = match[0];
var result = [
expression.slice(0, match.index),
expression.slice(match.index + splitString.length)
];
return result;
}
var expression = "Q101='You will have an answer here like a string for instance.'"
var regEx = new RegExp(/=|<>|like/)
var match = regEx.exec(expression)
if (match) {
var result = splitMatch(expression, match);
console.log(result);
}
While JavaScript's split method does have an optional limit parameter, it simply discards the parts of the result that make it too long (unlike, e.g. Python's split). To do this in JS, you'll need to split it manually, considering the length of the match —
const exp = "Q101='You will have an answer here like a string for instance.'"
const splitRxp = /=|<>|like/
const splitPos = exp.search(splitRxp)
const splitStr = exp.match(splitRxp)[0]
const result = splitPos != -1 ? (
[
exp.substring(0, splitPos),
exp.substring(splitPos + splitStr.length),
]
) : (
null
);
console.log(result)

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 to convert regex string to regex expression? [duplicate]

So I have a RegExp regex = /asd/
I am storing it as a as a key in my key-val store system.
So I say str = String(regex) which returns "/asd/".
Now I need to convert that string back to a RegExp.
So I try: RegExp(str) and I see /\/asd\//
this is not what I want. It is not the same as /asd/
Should I just remove the first and last characters from the string before converting it to regex? That would get me the desired result in this situation, but wouldn't necessarily work if the RegExp had modifiers like /i or /g
Is there a better way to do this?
If you don't need to store the modifiers, you can use Regexp#source to get the string value, and then convert back using the RegExp constructor.
var regex = /abc/g;
var str = regex.source; // "abc"
var restoreRegex = new RegExp(str, "g");
If you do need to store the modifiers, use a regex to parse the regex:
var regex = /abc/g;
var str = regex.toString(); // "/abc/g"
var parts = /\/(.*)\/(.*)/.exec(str);
var restoredRegex = new RegExp(parts[1], parts[2]);
This will work even if the pattern has a / in it, because .* is greedy, and will advance to the last / in the string.
If performance is a concern, use normal string manipulation using String#lastIndexOf:
var regex = /abc/g;
var str = regex.toString(); // "/abc/g"
var lastSlash = str.lastIndexOf("/");
var restoredRegex = new RegExp(str.slice(1, lastSlash), str.slice(lastSlash + 1));
const regex = /asd/gi;
converting RegExp to String
const obj = {flags: regex.flags, source: regex.source};
const string = JSON.stringify(obj);
then back to RegExp
const obj2 = JSON.parse(string);
const regex2 = new RegExp(obj2.source, obj2.flags);
Requires ES6+.
You can use the following before storage of your regex literal:
(new RegExp(regex)).source
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/source
Example:
regex = /asd/
string = (new RegExp(regex)).source
// string is now "asd"
regex = RegExp(string)
// regex has the original value /asd/
let rx = RegExp.apply(RegExp, str.match(/\/(.*)\/(.*)/).slice(1));
A modified version of #PegasusEpsilon answer
StackOverflow saves the day again, thanks #4castle! I wanted to store some regex rules in a JS file, and some in a DB, combine them into an array of objects like so:
module.exports = {
[SETTINGS.PRODUCTION_ENV]: [
{
"key": /<meta name="generator"[\s\S]*?>/gmi,
"value": "",
"regex": true
},
...
]
}
Then, loop through each environment's objects and apply it to a string of text. This is for a node/lambda project, so I wanted to use ES6. I used #4castle's code, with some destructuring, and I ended up with this:
let content = body;
const regexString = replacement.key.toString();
const regexParts = /\/(.*)\/(.*)/.exec(regexString);
const {1: source, 2: flags} = regexParts;
const regex = new RegExp(source, flags);
content = content.replace(regex, replacement.value);
return content;
Works a treat!

Passing Parameter into function match

I am using the function match for a search engine, so whenever a user types a search-string I take that string and use the match function on an array containing country names, but it doesn't seem to work.
For example if I do :
var string = "algeria";
var res = string.match(/alge/g); //alge is what the user would have typed in the search bar
alert(res);
I get a string res = "alge": //thus verifying that alge exists in algeria
But if I do this, it returns null, why? and how can I make it work?
var regex = "/alge/g";
var string = "algeria";
var res = string.match(regex);
alert(res);
To make a regex from a string, you need to create a RegExp object:
var regex = new RegExp("alge", "g");
(Beware that unless your users will be typing actual regular expressions, you'll need to escape any characters that have special meaning within regular expressions - see Is there a RegExp.escape function in Javascript? for ways to do this.)
You don't need quotes around the regex:
var regex = /alge/g;
Remove the quotes around the regex.
var regex = /alge/g;
var string = "algeria";
var res = string.match(regex);
alert(res);
found the answer, the match function takes a regex object so have to do
var regex = new RegExp(string, "g");
var res = text.match(regex);
This works fine

Regex remove repeated characters from a string by javascript

I have found a way to remove repeated characters from a string using regular expressions.
function RemoveDuplicates() {
var str = "aaabbbccc";
var filtered = str.replace(/[^\w\s]|(.)\1/gi, "");
alert(filtered);
}
Output: abc
this is working fine.
But if str = "aaabbbccccabbbbcccccc" then output is abcabc.
Is there any way to get only unique characters or remove all duplicates one?
Please let me know if there is any way.
A lookahead like "this, followed by something and this":
var str = "aaabbbccccabbbbcccccc";
console.log(str.replace(/(.)(?=.*\1)/g, "")); // "abc"
Note that this preserves the last occurrence of each character:
var str = "aabbccxccbbaa";
console.log(str.replace(/(.)(?=.*\1)/g, "")); // "xcba"
Without regexes, preserving order:
var str = "aabbccxccbbaa";
console.log(str.split("").filter(function(x, n, s) {
return s.indexOf(x) == n
}).join("")); // "abcx"
This is an old question, but in ES6 we can use Sets. The code looks like this:
var test = 'aaabbbcccaabbbcccaaaaaaaasa';
var result = Array.from(new Set(test)).join('');
console.log(result);

Categories

Resources