I need to add a variable inside a Character Class when using javascript regular expression. What I tried did not work. What the correct syntax for accomplishing this.
For example,
if(/[variable]/.test(Log))
{
}
You can use the following syntax
var re = new RegExp(variable);
and then use
re.test(Log)
Try this instead:
var regex = new RegExp(variable);
if(regex.test(Log)){
// your logic
}
Hope this will help !!
a='.*'
var patt=new RegExp(a);
patt.test('asdsd')
Actually,
if(/[variable]/.test(Log)) {
}
Is equivalent to:
if(new RegExp("["+variable+"]").test(Log)) {
}
Explanation:
Whenever you use a regex with the // notation, such as:
/[\d*]"+/
You can use the RegExp object and pass the regex as a escaped string. This way, the above regex is equivalent to:
new RegExp("[\\d*]\"+")
The modifiers can be passed as second argument. So that /anything/gm is the same as new RegExp("anything", "gm").
Related
I need to props few dynamic words regex inside child component with regex.
This is work:
In this situation my regex work but...
I need to regex some dynamic data which I don't know which is word is. All data is in my array.
What I am try?
Use the RegExp class constructor for your dynamic regexp:
const decorators = [
arrayOfWord.map((data) => {
// data is a string value:
// exp: data = Garnosny
// new RegExp(data, 'g') = /Garnosny/g
return { regex: new RegExp(data, 'g'), className: 'some css class' }
}
];
We have a couple of issues here...
1- In the second code snippet, you are missing a return statement in the arrow function passed to "map()".
2- In the third code snippet, you are calling "map()" again on the "data" array. But there is not clear what you are trying to do.
If you can explain a little bit better sure we can help.
I have a basic replace function, but I need it to perform a global replace, as it seems to be stopping on the first instance. I do not want to do it with a Regex. Applying the global attribute seems easy enough in most examples, but I am passing in a variable as the value to be replaced, and /g is having no impact. What am I doing wrong? Here is the example without the /g:
test string
"Why is my ^%friend so ^%? Maybe I need a ^!% one, abrand^!% one"
Simple replace function
function translate(oddStr) {
var tagDictionary = {};
tagDictionary['^%'] = 'odd';
tagDictionary['^!%'] = 'new';
Object.keys(tagDictionary).forEach( function (tag) {
oddStr = oddStr.replace(tag, tagDictionary[tag]);
});
return oddStr;
};
This function returns the first instance of each replaced, as expected. How can I apply /g to the tag variable in the forEach?
Use a split-join combo like this:
oddStr = oddStr.split(tag).join(tagDictionary[tag]);
"Why is my ^% friend so ^%? Maybe I need a ^!% one, abrand ^!% one".replace(/\^%/g, 'odd').replace(/\^!%/g, 'new')
"Why is my odd friend so odd? Maybe I need a new one, abrand new one"
If you need to create the regular expression from string, you can use RegExp constructor: new RegExp('\\^%', 'g').
If you don't have control over the tag-dictionary and it is coming from some external resource, then you will have to properly escape the tags.
Instead of using adhoc symbols for templating you should ideally use something like lodash.template
You need to escape your regex special characters (^=Start of string)
function translate(oddStr) {
var tagDictionary = {
'\\^%' : "odd",
'\\^!%' : 'new'
};
Object.keys(tagDictionary).forEach( function (tag) {
var r = new RegExp(tag, "g");
oddStr = oddStr.replace(r, tagDictionary[tag]);
});
return oddStr;
};
console.log(translate("Why is my ^%friend so ^%? Maybe I need a ^!% one, a brand ^!% one"));
I have a varible string like
var z = "anuj.working = false;anuj.downloadFile(event,'opp-for-download','anuj#anuj Demo Guide For Partners.pdf.zip (5.3 MB)','/file/dam/mail Anuj#anuj #Anuj Demo Guide For Partners.pdf.zip','zip',null)";
how can i convert it to a function. i don't want to use eval().
You can declare the variable string as a new function, then call that function:
var func = new Function(theFunctionString);
func();
I think this offers what you're looking for, but without having anuj. defined, I couldn't run a successful test.
If you concatenate in such a way as it from a JSON object, you can use JSON.parse to convert it to an object that will allow you to call it as a method of the object.
How would I make the following case insensitive?
if ($(this).attr("href").match(/\.exe$/))
{
// do something
}
Put an i after the closing slash of the regex.
So your code would look like this:
if ($(this).attr("href").match(/\.exe$/i))
With /i modifier:
if ($(this).attr("href").match(/\.exe$/i))
{
// do something
}
Another option would be to simply manipulate the case to what you want.
It appears as though you are trying to match against lowercase characters.
So you could do this:
if ($(this).attr("href").toLowerCase().match(/\.exe$/)) {
// do something
}
In fact, you could use .indexOf() instead of a regex if you wanted.
if ($(this).attr("href").toLowerCase().indexOf('.exe') > -1) {
// do something
}
Of course, this would match .exe in the middle of the string as well, if that's an issue.
Finally, you don't really need to create a jQuery object for this. The href property is accessible directly from the element represented by this.
if ( this.href.toLowerCase().match(/\.exe$/) ) {
// do something
}
if ($(this).attr("href").match(/\.exe$/i))
{
// do something
}
Unlike the match() function, the test() function returns true or false and is generally preferred when simply testing if a RegEx matches. The /i modifier for case insensitive matching works with both functions.
Example using test() with /i:
const link = $('a').first();
if (/\.exe$/i.test(link.attr('href')))
$('output').text('The link is evil.');
Fiddle with the code:
https://jsfiddle.net/71tg4dkw
Note:
Be aware of evil links that hide their file extension, like:
https://example.com/evil.exe?x=5
Documentation for test():
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
This question already has answers here:
How to check if a string "StartsWith" another string?
(18 answers)
Closed 3 years ago.
I know that I can do like ^= to see if an id starts with something, and I tried using that for this, but it didn't work. Basically, I'm retrieving a URL and I want to set a class for an element for path names that start in a certain way.
Example:
var pathname = window.location.pathname; //gives me /sub/1/train/yonks/459087
I want to make sure that for every path that starts with /sub/1, I can set a class for an element:
if (pathname ^= '/sub/1') { //this didn't work...
...
Use stringObject.substring
if (pathname.substring(0, 6) == "/sub/1") {
// ...
}
String.prototype.startsWith = function(needle)
{
return this.indexOf(needle) === 0;
};
You can use string.match() and a regular expression for this too:
if(pathname.match(/^\/sub\/1/)) { // you need to escape the slashes
string.match() will return an array of matching substrings if found, otherwise null.
A little more reusable function:
beginsWith = function(needle, haystack){
return (haystack.substr(0, needle.length) == needle);
}
First, lets extend the string object. Thanks to Ricardo Peres for the prototype, I think using the variable 'string' works better than 'needle' in the context of making it more readable.
String.prototype.beginsWith = function (string) {
return(this.indexOf(string) === 0);
};
Then you use it like this. Caution! Makes the code extremely readable.
var pathname = window.location.pathname;
if (pathname.beginsWith('/sub/1')) {
// Do stuff here
}
Have a look at JavaScript substring() method.