I would like to use a variable in RegExp in this function.
checkSocial(platform, link) {
let reg = new RegExp(/^(?:https?:\/\/)?(www\.facebook\.com\/)(?:\S+)/);
return reg.test(link);
}
Doing this:
let reg = new RegExp(`/^(?:https?:\/\/)?(www\.${platform}\.com\/)(?:\S+)/`);
or this:
let reg = new RegExp('^(?:https?:\/\/)?(www\.' + platform + '\.com\/)(?:\S+)');
didn't work. How can I add a variable?
You don't need the slashes when creating RegExp this way, it will add them automatically.
Also, note you would need extra escaping - I think the last \S token was not escaped properly?
This seems to be a more valid pattern:
let platform = 'facebook';
let reg1 = new RegExp(`^(?:https?:\/\/)?(www\.${platform}\.com\/)(?:\S+)`)
let reg2 = new RegExp(`^(?:https?:\/\/)?(www\.${platform}\.com\/)(?:\\S+)`)
console.log("1", reg1) // Outputs: /^(?:https?:\/\/)?(www.facebook.com\/)(?:S+)/
console.log("2", reg2) // Outputs: /^(?:https?:\/\/)?(www.facebook.com\/)(?:\S+)/
Related
I have a problem I can not solve. Let's say I have a variable that keeps the regExp pattern, that is to be provided by the user:
var pattern = this.state.regExpVal;
I also have a variable that keeps the value of textInput, meaning some piece of text, eg, postal codes.
var str = this.state.textAreaVal;
I create a new regExp object:
var myRegEx = new RegExp(pattern, 'g');
And the result is not ok:(it seems that the flag search globally is not working and I can not figure out why);
var result = str.match(myRegEx);
Can anyone help?
let reg = new RegExp("super", 'g');
"SOsuperISsuper!".match(reg);
The result is an Array with 2 Elements ["super","super"] as expected.
I guess the problem lies within your this some undefined or null values or in case-sense (try include 'i')
Edit:
let myObject = {
state: {
regExpVal: "super"
}
}
let reg = new RegExp(myObject.state.regExpVal, 'g');
"SOsuperISsuper!".match(reg);
Edit 2:
let myObject = {
state: {
regExpVal: "super"
}
};
let pattern = myObject.state.regExpVal;
let reg = new RegExp(pattern, 'g');
"SOsuperISsuper!".match(reg);
I think it would benefit you to provide a few concrete examples. It's difficult to help as well as would be possible without such. However, I can provide examples of how one constructs a regular expression from variables.
Let's assume your variable from which you wish to construct an "on-the-fly" regular expression matching pattern is
const someVar = 'LostInJavaScript';
Use of the Regular Expression constructor, as you seem to be using, is the necessary approach to take here. Inside the constructor, I tend to favor using ES2015-style string templates for the first argument passed it:
const regPattern = new RegExp(`${someVar}`, 'g');
// => /LostInJavaScript/g
Apply the relevant/appropriate String method (e.g., String#match, String#search, RegExp#test, RegExp#exec) passing it this dynamically created regular expression.
const strInput = 'RegularExpressionsHaveMeLostInJavaScript...',
matchedSubStr = strInput.match(regPattern);
// => ["LostInJavaScript"]
I have the following Regex that comes from a data Attribute on an HTML Element:
/^$|^[0-9]{2}.[0-9]{4}$/g
When I (manually) do:
/^$|^[0-9]{2}.[0-9]{4}$/g.test('01.2012');
It works and returns true.
When I put the Regex in a Variable like so:
var inputRegex = $(this).attr('data-validation');
And do:
inputRegex.test(input);
I get:
inputRegex.test is not a function.
I know that this is because inputRegex is a String and String does not have a test function, but when I create a RegExp object (new RegExp($(this).attr('data-validation')) it breaks my Regular Expression by escaping:
/\/^$|^[0-9]{2}.[0-9]{4}$\/g/
How can I use the data-attribute value as a Regular Expression? Please note that I cannot do: var regex = new RegExp(string, 'g'); because the Regular Expression(s) come predefined from the attribute.
var pattern = '\d+';
var regExp = new RegExp(pattern, 'g');
'1234dasf13241234'.match(regExp)
is it what you need?
var pattern = $(this).attr('data-validation');;
var regExp = new RegExp(pattern, 'g');
regExp.test(input);
in your case
your problem is that you need to retrieve the regex pattern from a attribute of an element, but it is returning string, and you want the string value to be like inline on your javascript code, like declaring plainly a regex. If this is really what you want to achieve, the closest solution is to use eval function, see updated code below:
var stringreg = "var inputRegex =" + $("#test").attr('data-validation') + ";"
eval(stringreg);
inputRegex.test(input);
This could help
var validation = "/^$|^[0-9]{2}.[0-9]{4}$/g"; //$(this).attr('data-validation')
var startIndex = validation.indexOf('/')+1
var lastIndex = validation.lastIndexOf('/');
var pattern = validation.substring(startIndex,lastIndex);
var options = validation.substring(lastIndex+1);
var regExp = new RegExp(pattern, options);
regExp.test('01.2012');
// true
Trying to get a filename and have it return a string.
try to turn:
plate-71-winter-hawk-final.jpg
into:
winter hawk final
where plate might also be uppercase. Here is what I have so far, doesn't seem to work
var theRegEx = new RegExp('[Plate|plate]-\d+-(.*).jpg');
var theString = "plate-71-winter-hawk-final.jpg"
var newString = theString.replace(theRegEx, theString);
newString;
Unfortunately, the "Rule #1" doesn't offer a better way:
var newString = theString.replace(/^[Pp]late-\d+-(.*)\.jpg$/, '$1')
.replace(/-/g, ' ');
Take care when you use a string with the object syntax to escape backslahes:
var theRegEx = new RegExp('^[Pp]late-\\d+-(.*)\\.jpg$');
Note that a character class is only a set of characters, you can't use it to put substrings and special regex characters loose their meaning inside it. [Plate|plate] is the same thing than [Pplate|]
You can write it like this too (without string):
var theRegEx = new RegExp(/^[Pp]late-\d+-(.*)\.jpg$/);
Try following script. It's not dependent on length of string as long as it follows standard pattern:
var data = "plate-71-winter-hawk-final.jpg";
var rx = /(?:plate\-\d+\-)(.*)(?=\.)/i;
var match = rx.exec(data);
if(match != null){
data = match[1];
data = data.replace(/\-/g, ' ');
}
console.log(data);
It will print:
winter hawk final
This question already has answers here:
JavaScript RegExp objects
(5 answers)
Closed 7 years ago.
I am trying to understand why writing regex as a string is not working but using it without string does work.
this is my example:
var patt = new RegExp("/test_.*/gi");
var res = patt.test("test_4");
console.log(res);
will return false
but this:
var patt = /test_.*/gi;
var res = patt.test("test_4");
console.log(res);
will return true
what is the difference
Your syntax of RegExp is wrong.
The delimiters are not required when you use RegExp constructor to create new Regular Expression.
The flags should be passed as second parameter to the RegExp constructor.
And . should to be escaped, if you want to match . literal.
Usage
var patt = new RegExp("test_.*", "gi");
Demo
var patt = new RegExp("test_.*", "gi");
var res = patt.test("test_4");
document.write(res);
The regexp constructor does not need delimiters, also, flags are isolated in another argument which simplifies it to
var patt = new RegExp('test_.*', 'gi');
var res = patt.test("test_4");
console.log(res);
You do not need to include the / at the start and end of the regular expression when using the constructor and the flags need to be in the second argument. See the MDN Documentation for RegExp.
var patt = new RegExp( "test_.*", "gi" );
var res = patt.test("test_4");
console.log(res);
You are not calling the constructor correctly, the falgs should be passed as a second parameter:
new RegExp('test_.*', 'gi');
As you can see in Documentation, it should respect this format:
new RegExp(pattern[, flags])
This is your demo:
var patt = new RegExp("test_.*", 'gi');
var res = patt.test("test_4");
alert(res);
I want to add a (variable) tag to values with regex, the pattern works fine with PHP but I have troubles implementing it into JavaScript.
The pattern is (value is the variable):
/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is
I escaped the backslashes:
var str = $("#div").html();
var regex = "/(?!(?:[^<]+>|[^>]+<\\/a>))\\b(" + value + ")\\b/is";
$("#div").html(str.replace(regex, "" + value + ""));
But this seem not to be right, I logged the pattern and its exactly what it should be.
Any ideas?
To create the regex from a string, you have to use JavaScript's RegExp object.
If you also want to match/replace more than one time, then you must add the g (global match) flag. Here's an example:
var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
In the general case, escape the string before using as regex:
Not every string is a valid regex, though: there are some speciall characters, like ( or [. To work around this issue, simply escape the string before turning it into a regex. A utility function for that goes in the sample below:
function escapeRegExp(stringToGoIntoTheRegex) {
return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
Note: the regex in the question uses the s modifier, which didn't exist at the time of the question, but does exist -- a s (dotall) flag/modifier in JavaScript -- today.
If you are trying to use a variable value in the expression, you must use the RegExp "constructor".
var regex = "(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b";
new RegExp(regex, "is")
I found I had to double slash the \b to get it working. For example to remove "1x" words from a string using a variable, I needed to use:
str = "1x";
var regex = new RegExp("\\b"+str+"\\b","g"); // same as inv.replace(/\b1x\b/g, "")
inv=inv.replace(regex, "");
You don't need the " to define a regular expression so just:
var regex = /(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is; // this is valid syntax
If value is a variable and you want a dynamic regular expression then you can't use this notation; use the alternative notation.
String.replace also accepts strings as input, so you can do "fox".replace("fox", "bear");
Alternative:
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(.*?)\b/", "is");
Keep in mind that if value contains regular expressions characters like (, [ and ? you will need to escape them.
I found this thread useful - so I thought I would add the answer to my own problem.
I wanted to edit a database configuration file (datastax cassandra) from a node application in javascript and for one of the settings in the file I needed to match on a string and then replace the line following it.
This was my solution.
dse_cassandra_yaml='/etc/dse/cassandra/cassandra.yaml'
// a) find the searchString and grab all text on the following line to it
// b) replace all next line text with a newString supplied to function
// note - leaves searchString text untouched
function replaceStringNextLine(file, searchString, newString) {
fs.readFile(file, 'utf-8', function(err, data){
if (err) throw err;
// need to use double escape '\\' when putting regex in strings !
var re = "\\s+(\\-\\s(.*)?)(?:\\s|$)";
var myRegExp = new RegExp(searchString + re, "g");
var match = myRegExp.exec(data);
var replaceThis = match[1];
var writeString = data.replace(replaceThis, newString);
fs.writeFile(file, writeString, 'utf-8', function (err) {
if (err) throw err;
console.log(file + ' updated');
});
});
}
searchString = "data_file_directories:"
newString = "- /mnt/cassandra/data"
replaceStringNextLine(dse_cassandra_yaml, searchString, newString );
After running, it will change the existing data directory setting to the new one:
config file before:
data_file_directories:
- /var/lib/cassandra/data
config file after:
data_file_directories:
- /mnt/cassandra/data
Much easier way: use template literals.
var variable = 'foo'
var expression = `.*${variable}.*`
var re = new RegExp(expression, 'g')
re.test('fdjklsffoodjkslfd') // true
re.test('fdjklsfdjkslfd') // false
Using string variable(s) content as part of a more complex composed regex expression (es6|ts)
This example will replace all urls using my-domain.com to my-other-domain (both are variables).
You can do dynamic regexs by combining string values and other regex expressions within a raw string template. Using String.raw will prevent javascript from escaping any character within your string values.
// Strings with some data
const domainStr = 'my-domain.com'
const newDomain = 'my-other-domain.com'
// Make sure your string is regex friendly
// This will replace dots for '\'.
const regexUrl = /\./gm;
const substr = `\\\.`;
const domain = domainStr.replace(regexUrl, substr);
// domain is a regex friendly string: 'my-domain\.com'
console.log('Regex expresion for domain', domain)
// HERE!!! You can 'assemble a complex regex using string pieces.
const re = new RegExp( String.raw `([\'|\"]https:\/\/)(${domain})(\S+[\'|\"])`, 'gm');
// now I'll use the regex expression groups to replace the domain
const domainSubst = `$1${newDomain}$3`;
// const page contains all the html text
const result = page.replace(re, domainSubst);
note: Don't forget to use regex101.com to create, test and export REGEX code.
var string = "Hi welcome to stack overflow"
var toSearch = "stack"
//case insensitive search
var result = string.search(new RegExp(toSearch, "i")) > 0 ? 'Matched' : 'notMatched'
https://jsfiddle.net/9f0mb6Lz/
Hope this helps