This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 7 years ago.
I want to pass variable values in the rule expression . Someone any way ?
like is :
var a = 'khuya'; var regex = /{a}/;
Like this:
var a = "khuya";
var regex = new RegExp( "{" + a + "}" );
Related
This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 3 years ago.
I need to replace hypen from string using Javascript but as per my code its not working.
function replace(){
var str='20-03-2019';
str.replace(/-/g,'/');
console.log(str);
}
replace();
Here I need to replace hypen(-) with / and output should like 20/03/2019.
String is immutable, so you need to do :
function replace(){
var str='20-03-2019';
str = str.replace(/-/g,'/');
alert('date ' + str);
}
replace();
This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 5 years ago.
/^([A-Za-z0-9]){1,8}$/
This is a normal way to write a regex in JavaScript but I want to construct the regex dynamically with a variable in between ().
Variable = [A-Za-z0-9]
This is how you can build a new regular expression from string:
var v = '[A-Za-z0-9]';
var regExp = new RegExp('^(' + v + '){1,8}$');
console.log(regExp);
Now you can use the regular expression regExp in your purpose
This question already has answers here:
Regular expression to find URLs within a string
(35 answers)
Closed 7 years ago.
I have this json object
arr[i].text
which returns
check this http://www.newlook.com/shop/womens/dresses/navy-short-sleeve-check-tunic-dress-_320165649
I want to return only the URL with a regex like so:
var urlreg = /(\bhttps?\:\/\/(www)?\.\w+\.\w+(\/[\w\d\-]+)*)/;
match = urlreg.exec(arr[i].text );
but doesn't work, is it something to with it being an object and not a string?
Try: var urlreg = /(https?:\/\/(\w+\.)+\w+(\/[\w\-_]+)+)/\/?
Here is a demo
This question already has answers here:
Get string inside parentheses, removing parentheses, with regex
(3 answers)
Closed 9 years ago.
I am trying to extract a string from within a larger string where i need to get the value only inside the brackets.
var str = 'ajay kumar (68766)';
Try this:
var str = 'ajay kumar (68766)';
str = str.slice(str.indexOf('(')+1, str.indexOf(')'));
How about using a regular expression?
var str = 'ajay kumar (68766)';
var output = str.replace(/^[\s\S]*?\((\d+)\)[\s\S]*?$/, '$1');
This question already has answers here:
How do I perform a Javascript match with a pattern that depends on a variable?
(3 answers)
Closed 8 years ago.
var seperator = ',', group = 'red, blue';
//group.search(seperator/g) - g is not defined
group.search(/seperator/g) // looks for "seperator"
group.search('/' + seperator + '/g') // doesn't seem to find my "seperator"
And with that I'm out of ideas... How do I get my seperator within expression?
Thanks in advance!
You need to create new regexp Object
var test = new RegExp(seperator, 'g');
group.search(test)