insert variable via forEach into regex expression [duplicate] - javascript

This question already has answers here:
Use dynamic (variable) string as regex pattern in JavaScript
(8 answers)
Closed 4 years ago.
As you can see below, I'm trying to count how many times a character in string J occurs in string S. The only issue is I can't put the argument o in the forEach loop into the regex expression as shown in the console.log.
var numJewelsInStones = function(J, S) {
let jArr = J.split('');
let sArr = S.split('');
jArr.forEach(o=>{
console.log(S.replace(/[^o]/g,"").length);
})
};
numJewelsInStones("aA", "aAAbbbb");

You can create regular expression with constructor function where you pass string parameters:
new RegExp('[^' + o + ']', 'g')
Your replace logic might look like:
S.replace(new RegExp('[^' + o + ']', 'g'), '')

Related

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

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

Spliting a string with multiple delimiters from an array [duplicate]

This question already has answers here:
Is there a RegExp.escape function in JavaScript?
(18 answers)
Closed 3 years ago.
I need to split a string by multiple delimiters.
My string is var str = "2$4#3*5"
My array of delimiters (separators) is var del = ["$","#", "*"]
I'm using a regular expression but it is not working.
str.split(new RegExp(del.join('|'), 'gi'));
The results should be ["2","4","3","5"]
However I'm getting an error SyntaxError: Invalid regular expression: /*/: Nothing to repeat
When I remove the * the resulting array is ["2$3',"3", "5"]
How can I split with multiple delimiters from an array of delimiters?
and why does this not work with $ and *?
You need to escape the special characters first - replace function from this answer:
var str = "2$4#3*5";    
var del = ["$", "#", "*"];    
const res = str.split(new RegExp(del.map(e => e.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).join("|"), "gi"));
    
console.log(res);
Try like this.
I passed in the Regex expression in split.
var str = "2$4#3*5"
var res= str.split(/[$,#,*]+/)
console.log(res)

Function to split a phrase of the form "fooBar" into "foo bar" in javascript? [duplicate]

This question already has answers here:
Split by Caps in Javascript
(4 answers)
Closed 8 years ago.
What's the best way to have a function that takes in a phrase of the form fooBar and returns the words foo bar?
My current approach of iterating over all characters to find a capitalized letter and then splitting on that index seems suboptimal is there a better way?
Thanks!
Your approach is the good one, that is exactly what split function does with this pattern: (?=[A-Z])
var resultArray = mystring.split(/(?=[A-Z])/);
The pattern uses a lookahead assertion (?=...) that means followed by.
Note: if you want to make lowercase all items of the result array, you can map the array like this:
resultArray = resultArray.map(function (x){ return x.toLowerCase(); });
The answer here suffices: Split by Caps in Javascript
Basically use a regex that looks for caps and does a split. To be complete the function is
function splitFooBar() {
var fb = fooBar.split(/(?=[A-Z])/);
fbString = fb.length > 1? fb[0] + " " + fb[1].substr(0, 1).toLowerCase() + fb[1].substr(1): fb[0];
return fbString;
}
try this
var re = /([A-Z])/g;
var str = 'fooBar fooBar fooBarww oldWman ';
var subst = ' $1';
var result = str.replace(re, subst);
result = result.toLowerCase();
console.log(result)
alert(result)

How to dynamically create regex to use in .match Javascript? [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 8 years ago.
I need to dynamically create a regex to use in match function javascript.
How would that be possible?
var p = "*|";
var s = "|*";
"*|1387461375|* hello *|sfa|* *|3135145|* test".match(/"p"(\d{3,})"s"/g)
this would be the right regex: /\*\|(\d{3,})\|\*/g
even if I add backslashes to p and s it doesn't work. Is it possible?
RegExp is your friend:
var p = "\\*\\|", s = "\\|\\*"
var reg = new RegExp(p + '(\\d{3,})' + s, 'g')
"*|1387461375|* hello *|sfa|* *|3135145|* test".match(reg)
The key to making the dynamic regex global is to transform it into a RegExp object, and pass 'g' in as the second argument.
Working example.
You can construct a RegExp object using your variables first. Also remember to escape * and | while forming RegExp object:
var p = "*|";
var s = "|*";
var re = new RegExp(p.replace(/([*|])/g, '\\$1')
+ "(\\d{3,})" +
s.replace(/([*|])/g, '\\$1'), "g");
var m = "*|1387461375|* hello *|sfa|* *|3135145|* test".match(re);
console.log(m);
//=> ["*|1387461375|*", "*|3135145|*"]

JavaScript Find and replace with variable in regular expression [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Regular Expression Pattern With A Variable
function function1() {
var key = "name";
var sample = "param.name['key'] = name; param.name[i] = 1000; param.name1[i] = name1;";
var result = result.replace(/param.<<name>>\[(\d+)\]/g, 'parameter[prefix_$1]');
}
Expected result: parameter['prefix_key'] = name; parameter['prefix_i'] = 1000;
I cant add variable key into the replace function in regular expresssion.
Please help how to construct the regular expression in replace
You can make a regex out of a string by making a RegExp object:
var regex = new RegExp("param\\." + name + "\\[(\d+)\\]", "g")
var result = result.replace(regex, 'parameter[prefix_$1]');

Categories