Confused why my regex expression isn't working? [duplicate] - javascript

This question already has answers here:
Alternation operator inside square brackets does not work
(2 answers)
What's the difference between () and [] in regular expression patterns?
(6 answers)
Closed 3 years ago.
Attempting to create a regex expression that splits a string at ',' and '\n' and then a passed in custom delimiter (which is signified by firstChar in my code).
Format for the string being passed in: {delimiter}\n{numbers}. I've used regex101 online and it seems to work on there but in my actual code it doesn't split at the custom delimiter so not sure what I'm doing wrong.
if (str.includes('\n')) {
let firstChar = str.slice(0, 1);
if (parseInt(firstChar)) {
strArr = str.split(/,|\n/) ;
} else {
strArr = str.split(/[,|\n|firstChar]/);
}
}
expect ';\n2;5' to equal 7 but my array splits into [";", "2;5"] for some reason.

Your first character isn't a number so you go to else condition directly, if you want a dynamic regex then you need to build it using RegExp
Also you don't need character class here
/[,|\n|firstChar]/
it should be
/,|\n|firstChar/
let splitter = (str) => {
if (str.includes('\n')) {
let firstChar = str.slice(0, 1);
if (parseInt(firstChar)) {
return str.split(/,|\n/);
} else {
let regex = new RegExp(`,|\\n|\\${firstChar}`, 'g') // building a dynamic regex here
return str.split(regex).filter(Boolean)
}
}
}
console.log(splitter(";\n2;5"))
console.log(splitter("*\n2*5"))

Related

How to remove + from string except at beginning using regex [duplicate]

This question already has answers here:
Replace all occurrences of character except in the beginning of string (Regex)
(3 answers)
Remove all occurrences of a character except the first one in string with javascript
(1 answer)
Closed 1 year ago.
I’m looking to remove + from a string except at the initial position using javascript replace and regex.
Input: +123+45+
Expected result: +12345
Please help
const string = '+123+45+'
console.log(string.replace(/([^^])\+/g, '$1'))
https://regexr.com/61g3c
You can try the below regex java script. Replace all plus sign except first occurrence.
const givenString = '+123+45+'
let index = 0
let result = givenString.replace(/\+/g, (item) => (!index++ ? item : ""));
console.log(result)
input = '+123+45+';
regex = new RegExp('(?!^)(\\+)', 'g');
output = input.replace(regex, '');
console.log(output);

Javascript first complete unicode character from a string [duplicate]

This question already has answers here:
Difference between codePointAt and charCodeAt
(3 answers)
Closed 2 years ago.
Getting the first character in a string is fairly straightforward.
const str = 'abc'
str[0] // 'a'
However, when javascript sees a unicode string, it will return the first byte of a multi-byte unicode character.
const strUnicode = '💖hi'
strUnicode[0] // '�'
Is it possible to return the first complete unicode character?
const strUnicode = '💖hi'
f(strUnicode) // '💖'
Issue is that symbols are 16-bit characters. So it takes 2 positions in a character array.
Idea:
Loop over string and validate if current character is a symbol or not.
If symbol, take character at i and i+1. Increment i to skip the processed character
If not, just pick one character
function getCharacters(str) {
const parts = []
for(let i = 0; i< str.length; i++) {
if (str.charCodeAt( i ) > 255) {
parts.push(str.substr(i, 2))
i++
} else {
parts.push(str[i])
}
}
return parts
}
const strUnicode = '💖hi'
console.log( getCharacters(strUnicode) )

Match strings using asterisks (wildcards) [duplicate]

This question already has answers here:
Wildcard string comparison in Javascript
(10 answers)
Closed 4 years ago.
I want to test if any string in an array matchs with a particular string. However, the strings in array may contain the asterisks pattern.
var toTest = ["foo_*", "*foo_1", "foo_1*", "bar", "*foo"];
var toMatch = "foo_1";
For this sample, the result will be true because foo_*, *foo_1 and foo_1* will match with foo_1, but bar and *foo won't.
I have tried to use split function with lodash _.some but it seems overcomplicated and I can't make it works consistently.
function isMatching() {
return _.some(toTest , function(a) {
return _.some(a.split("*"), function(part1, idx1) {
return (part1.length && _.some(toMatch.split(part1), function(part2, idx2) {
return (part2.length && idx1 == idx2);
}));
});
});
}
To achieve expected result, use below option of using filter, indexOf and replace
var toTest = ["foo_*", "*foo_1", "foo_1*", "bar", "*_foo"];
var toMatch = "foo_1";
console.log(toTest.filter(v => toMatch.indexOf(v.replace('*', '')) !== -1))

How can I create an array including all matches of a regex in JavaScript? [duplicate]

This question already has an answer here:
Put all regex matches in an array?
(1 answer)
Closed 6 years ago.
I have this function which is supposed to put all matches regex returns when executed against a string str into the array res and then return it:
function matchAll(str, regex) {
var res = [];
var m;
while (m = regex.exec(str)) {
res.push(m[0]);
}
return res;
}
It creates an infinite loop with the regex /^\d\d*/i. Why?
Try this regex: \d\s[A-Z0-9]{3,3}
RegexPal (working solution): http://www.regexpal.com/?fam=96072

Convert a letter string to a pure letter for use in .match regex [duplicate]

This question already has answers here:
Create RegExps on the fly using string variables
(6 answers)
Closed 8 years ago.
I have an array of alphabets in the form of letter strings
alpha = ['a','b', etc..];
I'm counting up numbers of each letter in a word like so
for (j=0;j<alpha.length;j++){
num = word.match(/alpha[j]/g).length;}
Problem is that, for example, alpha[0] is 'a', not a and match regex only recognizes a .
How can I convert from 'a' to a so that match recognizes it?
To clarify
"ara".match(/a/g) returns ["a","a"] while "ara".match(/'a'/g) returns null.
You can construct a RegExp from a string with the RegExp constructor as described here.
for (j=0;j<alpha.length;j++){
var matches = word.match(new RegExp(alpha[j], "g"));
if (matches) {
num = matches.length;
// other code here to process the match
}
}
This assumes that none of the characters in the alpha array will be special characters in a regular expression because if they are, you will have to escape them so they are treated as normal characters.
As jfriend00 suggests, you can use the RegExp constructor like:
var re, num, matches;
for (j=0; j<alpha.length; j++){
re = new RegExp(alpha[j],'g');
matches = word.match(re);
num = matches? matches.length : 0;
}
Note that another way (shorter, faster, simpler) is:
var num = word.split('a').length - 1; // 'ara' -> 2

Categories