Join Regex Expression Array - javascript

I have an array of words e.g. apple, banana, horse which I want to have in a later function as split points.
I found this how to concat regex expressions, but it is for a fixed number of expressions:
How can I concatenate regex literals in JavaScript?
Question:
How to join an array of regex expressions?
filterTemp = [];
for (i = 0, len = filterWords.length; i < len; i++) {
word = filterWords[i];
filterTemp.push(new RegExp("\b" + word + "\b"));
}
filter = new RegExp(filterTemp.source.join("|"), "gi");
return console.log("filter", filter);

You don't need to construct RegExp inside loop just keep pushing strings into temp array and then use join only once outside to construct RegExp object:
var filterWords = ['abc', 'foo', 'bar'];
var filterTemp = [];
for (i = 0, len = filterWords.length; i < len; i++) {
filterTemp.push("\\b" + filterWords[i] + "\\b");
}
filter = new RegExp(filterTemp.join("|"), "gi");
console.log("filter", filter);
//=> /\babc\b|\bfoo\b|\bbar\b/gi

In 2022:
const validate = (val: string) => {
const errorMessage =
'Enter the time separated by commas. For example: 12:30, 22:00, ... etc.';
const values = val.split(',').map((val: string) => val.trim());
const filter = new RegExp(/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/);
const isValid = values.some(
(value: string) => !filter.test(value),
);
return !isValid || errorMessage;
}

Related

Need Regular Expression to fetch string data from array with exact match

I want to match and store string in an array using javascript and need regular expression for this. Other solution also appreciated. separated by '_' if only both matches in string those string from array should be retured only, no other match should be accepted. Array and search string both are dynamic. Below is just an example but solution shoud match for any dynamic data.
Example problem given below.
let arr1 = ['ef','cd','ab','cdab','efab','cdef','ab/cd/ef','cd/ef,ab','cd/ab','ab/ef']
test scenarios:
let search = 'ef_ab';
expected output would be ['efab','ab/ef']
let search = 'ab_cd_ef';
expected output would be ['ab/cd/ef','cd/ef,ab']
let search = 'cd';
expected output would be ['cd']
Any help in javascript for problem is appreciated.
I have tried below regex and looping.
Here word1 for given example could be ab or cd or ef and same could be for word2 , word3
let arr1 = ['ef', 'cd', 'ab', 'cdab', 'efab', 'cdef', 'ab/cd/ef', 'cd/ef,ab', 'cd/ab', 'ab/ef']
let regex = /(?=.*word1)(?=.*word2)(?=.*word3)/;
let arr2 = [];
for (i = 0; i < arr1.length; i++) {
if (regex.test(arr1[i]))
arr2.push(arr1[i]);
}
console.log(arr2)
You may use the input to form a series of regex patterns, each of which must match against the input string. An input which matches all regex patterns is a valid match.
var arr1 = ['ef','cd','ab','cdab','efab','cdef','ab/cd/ef','cd/ef,ab','cd/ab','ab/ef'];
var search = 'ab_cd_ef';
var parts = search.split("_");
for (var i=0; i < arr1.length; ++i) {
var counter = 0;
for (var p=0; p < parts.length; ++p) {
var r = new RegExp("\\b" + parts[p] + "\\b");
if (r.test(arr1[i])) {
++counter;
}
}
if (counter == parts.length) {
console.log(arr1[i] + " => MATCH");
}
}
We need to get some permutations going:
// Heap's algorithm https://stackoverflow.com/a/66122464/295783
const excluding = (i) => (xs) => [... xs.slice (0, i), ... xs.slice (i + 1)];
const permutations = (xs) => xs.length == 0 ? [[]] : xs.flatMap ((x, i) => permutations (excluding (i) (xs)).map (p => (x +' '+ p).trim()));
const findSequence = (arr,str) => {
const parts = str.split("_");
const re = new RegExp(`^${permutations(parts) // ^ from start
.map(part => `${part.replace(/ /g,".?")}`) // with a character or not in between
.join('|')}$`); // to end $ of each string
console.log(re); // just to show the resulting regexp
return arr.filter(item => item.match(re));
}
let arr1 = ['ef', 'cd', 'ab', 'cdab', 'efab', 'cdef', 'ab/cd/ef', 'cd/ef,ab', 'cd/ab', 'ab/ef']
console.log(findSequence(arr1,'ef_ab')) // ['efab','ab/ef']
console.log(findSequence(arr1,'ab_cd_ef')) // ['ab/cd/ef','cd/ef,ab']
console.log(findSequence(arr1,'cd')) // ['cd']

How to extract specific words from a string with some patterns?

I am trying to extract some strings from a word with some pattern like -
"38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"
how will I extract all word between - separately, means first word before - and then second word between - and - and so on...
string = "38384-1-page1-2222";
string.substr(0, string.indexof("-")); //return 38384
But how will I extract 1, page1 and 2222 all the words separately?
The javascript function str.split(separator) split the string by the given separator and it returns an array of all the splited string. REF Here
Here is an example following your question :
var string = "38384-1-page1-2222";
var separator = "-";
var separated = string.split(separator);
var firstString = separated[0]; // will be '38384'
var secondString = separated[1]; // will be '1'
var thirdString = separated[2]; // will be 'page1'
/* And So on ... */
Hope this can help
Use String.prototype.split() to get your string into array
var words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
var resultArray = [];
for (let i = 0; i < words.length;i++) {
let temp = words[i];
resultArray = pushArray(temp.split("-"), resultArray)
}
console.log(resultArray)
function pushArray (inputArray, output) {
for (let i = 0; i < inputArray.length;i++) {
output.push(inputArray[i]);
}
return output;
}
Or simply use Array.prototype.reduce()
var words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
var result = words.reduce((previousValue, currentValue) => previousValue.concat(currentValue.split("-")), [])
console.log(result)
You can use regex /[^-]+/g
const words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
console.log(words.map(v=>v.match(/[^-]+/g)).flat())

Splitting string into array based on first and last

I have this array :-
var a = [' DL1,C1,C5,C6','M4,DL3-7,B1-5']
And I want to split them like
[DL1,C1,C5,C6,M4,DL3,DL4,DL5,DL6,DL7,B1,B2,B3,B4,B5]
So that DL3-7 or DL3-DL7 this Split like this DL3,DL4,DL5,DL6,DL7
Reason why I am doing this, is because I want to block duplicate entry like DL3 should not come anywhere else, I am trying for loops to do this, just want to know if there is any simpler way to do it, and check for duplicacy afterwards.
Thanks
You have to break down your problems into three parts:
getting comma delimited values into different array items
resolving "DL3-7" to "DL3", "DL4"...
removing duplicates
Once you break down the problem, it is much easier to handle them one by one. The code is pretty readable, let me know if there is anything difficult to understand what's going on.
const a = ['DL1,C1,C5,C6', 'M4,DL3-7,B1-5']
//this will split all comma delimited values
const commaDelimit = a.map(item => item.split(',')).flat();
console.log("Separate values by comma: ")
console.log(commaDelimit);
//this will turn the ranges into individual items
//this does not account for if the number is bigger than 9.
//you can try doing this part yourself if you need to, should be a good learning exercise.
const resolveRange = commaDelimit.map(item => {
if (item.includes('-')) {
const pos = item.indexOf('-');
const beginning = Number(item.charAt(pos - 1));
const end = Number(item.charAt(pos + 1)) + 1;
const toReturn = [];
const prependString = item.substring(0, pos - 1);
for (let i = beginning; i < end; i++) {
toReturn.push(`${prependString}${i}`)
}
return toReturn;
}
return item;
}).flat();
console.log("Change 'DL3-7' to DL3, DL4 and so on: ")
console.log(resolveRange);
//this will get rid of duplicates
const uniques = [...new Set(resolveRange)];
console.log("Remove duplicates: ")
console.log(uniques);
Create an Array with that length, iterate and transform,
I've just wrote the most challenged part:
function splitRange(range) {
let a = range.split('-');
if (a.length < 2) return [range];
const baseString = (a[0].match(/[a-z A-Z]/g))?.join('');
const baseNumber = +((a[0].match(/\d+/))?.shift());
return Array.from({length: +a.pop().match(/\d+/) - baseNumber + 1}).map((_,i)=>`${baseString}${i+baseNumber}`);
}
const s='DL1,C1,C5,C6,M4,DL3-7,B1-5';
console.log(
s.split(',').map(item=>splitRange(item)).flat()
);
Basically, #cSharp has explained the concept of data transformation to the desired output.
Split by comma.
Work with regex to transform the range value and append it to the array. Regex pattern & test data
Distinct the array value.
var a = [' DL1,C1,C5,C6','M4,DL3-7,B1-5'];
var formatteds = a.reduce((previous, current) => {
var splits = current.trim().split(',');
var rangedSplits = splits.reduce((prev, cur) => {
var pattern = new RegExp(/([A-Z]*)(\d)-[A-Z]*(\d)/);
var match = pattern.exec(cur);
if (match) {
// Pattern 1: ['DL3-7', 'DL', '3', '7']
// Pattern 2: ['DL3-DL7', 'DL', '3', '7']
var startIndex = parseInt(match[2].toString());
var endIndex = parseInt(match[3].toString());
var arr = [];
for (let i = startIndex; i <= endIndex; i++) {
arr.push(match[1].toString() + i);
}
prev = prev.concat(arr);
} else {
prev = prev.concat([cur]);
}
return prev;
}, []);
previous = previous.concat(rangedSplits);
return previous;
}, []);
var result = formatteds.filter((x, i, array) => array.indexOf(x) === i);
console.log(result);

Json from string using regular expression

I have a string like:
const stringVar = ":20:9077f1722efa3632 :12:700 :77E: :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE"
I want to create JSON from above stringVar:
{
":21:" : "9077f1722efa3632",
":12:" : "700",
":27A:": "2/2",
":21A:": "9077f1722efa3632",
":27:" : "1/2",
":40A:": "IRREVOCABLE"
}
So, I was thinking I could split with regular expression (":(any Of char/digit):")
I would make the first part the key and the second part its value.
The regular expression /(:\w+:)(\S+)/ matches the whole key:value pair. You can add the g modifier, and then use it in a loop to get all the matches and put them into the object.
const stringVar = ":20:9077f1722efa3632 :12:700 :77E: :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE"
var regexp = /(:\w+:)(\S+)/g;
var obj = {};
var match;
while (match = regexp.exec(stringVar)) {
obj[match[1]] = match[2];
}
console.log(obj);
If you want to create an array of {key: ":20:", value: "9077f1722efa3632"}, you can modify the code to:
const stringVar = ":20:9077f1722efa3632 :12:700 :77E: :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE"
var regexp = /(:\w+:)(\S+)/g;
var array = [];
var match;
while (match = regexp.exec(stringVar)) {
array.push({key: match[1], value: match[2]});
}
console.log(array);
If the values can contain space, change the regexp to:
/(:\w+:)([^:]+)\s/g
This will match anything not containing : as the value, but not include the last space.
You can achieve the same result without using regex.
const stringVar = ":20:9077f1722efa3632 :12:700 :77E:xxx :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE";
const result = stringVar
.split(' ')
.reduce((ret, current) => {
const pos = current.indexOf(':', 1);
ret[current.substring(0, pos + 1)] = current.substring(pos + 1);
return ret;
}, {});
console.log(result);

Remove duplicate in a string - javascript

I have a string in javascript where there are a lot of duplicates. For example I have:
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
What can I do to delete duplicates and to get for example x="Int32,Double"?
With Set and Array.from this is pretty easy:
Array.from(new Set(x.split(','))).toString()
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
x = Array.from(new Set(x.split(','))).toString();
document.write(x);
If you have to support current browsers, you can split the array and then filter it
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
var arr = x.split(',');
x = arr.filter(function(value, index, self) {
return self.indexOf(value) === index;
}).join(',');
document.body.innerHTML = x;
Use new js syntax remove Dupicate from a string.
String.prototype.removeDuplicate = Function() {
const set = new Set(this.split(','))
return [...set].join(',')
}
x.removeDuplicate()
function myFunction(str) {
var result = "";
var freq = {};
for(i=0;i<str.length;i++){
let char = str[i];
if(freq[char]) {
freq[char]++;
} else {
freq[char] =1
result = result+char;
}
}
return result;
}
That is a more readable and better parameterized solution:
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
var removeDup = [...new Set(x.split(","))].join(",");
//result "Int32,Double"
Check This out -
removeDuplicates() function takes a string as an argument and then the string split function which is an inbuilt function splits it into an array of single characters. Then the arr2 array which is empty at beginning, a forEach loop checks for every element in the arr2 - if the arr2 has the element it will not push the character in it, otherwise it will push. So the final array returned is with unique elements. Finally we join the array with the join() method to make it a string.
const removeDuplicates = (str) => {
const arr = str.split("");
const arr2 = [];
arr.forEach((el, i) => {
if (!arr2.includes(el)) {
arr2.push(el);
}
});
return arr2.join("").replace(",", "").replace("", " ");
};
console.log(removeDuplicates( "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"));
Its simple just remove duplicates in string using new Set and join them.
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
console.log([...new Set(x)].join(""));
function removeDups(s) {
let charArray = s.split("");
for (let i = 0; i < charArray.length; i++) {
for (let j = i + 1; j < charArray.length; j++)
if (charArray[i] == charArray[j]) {
charArray.splice(j, 1);
j--;
}
}
return charArray.join("");
}
console.log(removeDups("Int32,Int32,Int32,InInt32,Int32,Double,Double,Double"));
You can use Set()
const result = Array.from(new Set(x)).join('')
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
const result = Array.from(new Set(x)).join('')
console.log(result)
you can use the replaceAll function:
let str = "/Courses/"
let newStr = str.replaceAll('/', '')
console.log(newStr) // result -> Courses
function removeDuplicate(x)
{
var a = x.split(',');
var x2 = [];
for (var i in a)
if(x2.indexOf(a[i]) == -1) x2.push(a[i])
return x2.join(',');
}
const str = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
const usingSpread = [...str]
const duplicatesRemove = [...new Set(usingSpread)]
const string = duplicatesRemove.join("")
console.log("After removing duplicates: " + string)
STEPS
convert string to character array using spread operator
new Set will implicitly remove duplicate character
convert character array to string using join("") method

Categories

Resources