How to define the 'case insensitive' modifier i in a regex? [duplicate] - javascript

This question already has answers here:
Case insensitive regex in JavaScript
(5 answers)
Closed 2 years ago.
Given the following JavaScript code:
var res = 'text';
var regex = new RegExp(res);
var str = 'My text';
if (str.match(regex)) {
alert('found word');
}
I need to inform RegExp that theres variable can be uppercase or lowercase. Something like this: str.match (regex / i).

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
new RegExp(res, 'i')
Is what you need.

Related

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)

Javascript regex test from variable [duplicate]

This question already has answers here:
Backslashes - Regular Expression - Javascript
(2 answers)
Closed 6 years ago.
I have an problem with constructing regex from variable.
var a = '.playlist-item:nth-child(2n+1)';
var selector = /.playlist-item:nth-child\(2n\+1\)/g;
var s = '.playlist-item:nth-child\(2n\+1\)';
console.log(selector.test(a))//true
var reg = new RegExp(s,"g");
console.log(reg.test(a) )//false
Second is false because I have string quotes around it (I think), how do I construct regexp from string?
https://jsfiddle.net/eq3eu2e8/1/
For a string you have to use double backslashes if you want to include them in the string:
var a = '.playlist-item:nth-child(2n+1)';
var selector = /.playlist-item:nth-child\(2n\+1\)/g;
var s = '.playlist-item:nth-child\\(2n\\+1\\)';
console.log(selector.test(a)); //true
var reg = new RegExp(s,"g");
console.log(reg.test(a)); //false

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|*"]

RegEx extract all real numbers from a string [duplicate]

This question already has answers here:
Regex exec only returning first match [duplicate]
(3 answers)
Closed 8 years ago.
This regex in JavaScript is returning only the first real number from a given string, where I expect an array of two, as I am using /g. Where is my mistake?
/[-+]?[0-9]*\.?[0-9]+/g.exec("-8.075090 -35.893450( descr)")
returns:
["-8.075090"]
Try this code:
var input = "-8.075090 -35.893450( descr)";
var ptrn = /[-+]?[0-9]*\.?[0-9]+/g;
var match;
while ((match = ptrn.exec(input)) != null) {
alert(match);
}
Demo
http://jsfiddle.net/kCm4z/
Discussion
The exec method only returns the first match. It must be called repeatedly until it returns null for gettting all matches.
Alternatively, the regex can be written like this:
/[-+]?\d*\.?\d+/g
String.prototype.match gives you all matches:
var r = /[-+]?[0-9]*\.?[0-9]+/g
var s = "-8.075090 -35.893450( descr)"
console.log(s.match(r))
//=> ["-8.075090", "-35.893450"]

Regex match text between tags [duplicate]

This question already has answers here:
Regular expression to get a string between two strings in Javascript
(13 answers)
Closed 4 years ago.
I have this string:
My name is <b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.
I'd like to get the text between b tags to an array, that is:
['Bob', '20', 'programming']
I tried this /<b>(.*?)<\/b>/.exec(str) but it will only get the first text.
/<b>(.*?)<\/b>/g
Add g (global) flag after:
/<b>(.*?)<\/b>/g.exec(str)
//^-----here it is
However if you want to get all matched elements, then you need something like this:
var str = "<b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";
var result = str.match(/<b>(.*?)<\/b>/g).map(function(val){
return val.replace(/<\/?b>/g,'');
});
//result -> ["Bob", "20", "programming"]
If an element has attributes, regexp will be:
/<b [^>]+>(.*?)<\/b>/g.exec(str)
var root = document.createElement("div");
root.innerHTML = "My name is <b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";
var texts = [].map.call( root.querySelectorAll("b"), function(v){
return v.textContent || v.innerText || "";
});
//["Bob", "20", "programming"]
Use match instead, and the g flag.
str.match(/<b>(.*?)<\/b>/g);
Try
str.match(/<b>(.*?)<\/b>/g);

Categories