This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 2 years ago.
I want to replace {$variable_name} in a string,like "Hi, my name is {$name}." will be change to "Hi, my name is Sam."
I thought $ will be represented as \$, many RegExp test websites, like, https://www.regextester.com/, do the same.
My code is followed.
var str = "Hi, my name is {$name}.";
var reg = "\{\$name\}";
str = str.replace(new RegExp(reg,"g"), "Sam");
console.log(str); //Hi, my name is {$name}.
Then, I change the \$ to \\$, it worked.
var str = "Hi, my name is {$name}.";
var reg = "\{\\$name\}";
str = str.replace(new RegExp(reg,"g"), "Sam");
console.log(str); //Hi, my name is Sam.
But I don't understand why, maybe my poor search skills, I didn't find an explanation.
Can anyone explain this to me? Thank you very much.
The reason for this is the way you are writing the regular expression. In a string, the \ character is used to escape, that is what is causing the behaviour you are seeing here. There is another way to write regular expressions which follows the same rules as these regex testing websites use. The difference is just wrapping the string in forward slashes instead of quotes.
var reg = /\{\$name\}/;
is the same as
var reg = "\{\\$name\}";
Related
This question already has answers here:
How to remove numbers from a string?
(8 answers)
Closed 3 years ago.
I have a few URL's like these
https://{Domain}/rent/abcdef/2019/Canada
https:/{Domain}/buy/Supported/2019/Gill-Avenue
I want to remove '2019'or any part which contain only numbers from these Url's so that the Url's look as below
https://{Domain}/rent/abcdef/Canada
https:/{Domain}/buy/Supported/Gill-Avenue
How can i achieve this using javascript
You can try this;
let str = "https://test.com/rent/abcdef/2019/Canada";
str.replace(/\/\d+/g, '');
You should try something like that:
split on '/', filter with a /d regex and rejoin with '/'
I can't try right now sorry
window.location.href.split('/').filter(substr => !(/^\d+$/.match(substr))).join('/')
Try to do this for the first:
var str = "https://example.com/rent/abcdef/2019/Canada"
str = str.replace(/[0-9]/g, '');
str = str.replace("f//", "f/");
And for the second:
var str = "https://example.com/rent/abcdef/2019/Canada"
str = str.replace(/[0-9]/g, '');
str = str.replace("d//", "d/");
So this is if you want to replace just 1 digit. The first one of each of these works but adds a new / backslash to the whole link after the last letter before the / in the old version. To remove that, you do the second, which contains the last letter to not remove the :// too. The way is to find the last letter of each of these numbers before the backslash after using the first replace() function and replace them to remove the extra backslash.
This might work for easy things, like if you already know the URL, but for complicated things like a very big project, this is no easy way to do it. If you want "easy", then check other answers.
As said, you can also do this:
let str = "https://test.com/rent/abcdef/2019/Canada";
var withNoNum = str.replace(/\/\d+/g, '');
This is going to remove groups of numbers. So I added a new string withNoNum which is str's replacement with no numbers, which might be more good because if you are doing a website that allows you to send your own website and remove the numbers from it to get a new site.
This also might help you with this problem: removing numbers from string
This question already has answers here:
JavaScript RegExp objects
(5 answers)
Closed 6 years ago.
I am trying to validate if a string I entered matches the date format 'MM/yyyy'
Below is a sample of the code I am using for the same:
var date='05/2016'
var patt= new RegExp('^((0[1-9])|(1[0-2])|[1-9])\/(\d{4})$');
patt.test(date);
However the above code is returning false.
I tried running it with the regex checker:
https://regex101.com/
The pattern seems to be working fine.
Could someone please let me know what is missing.
https://jsfiddle.net/ymj6o8La/
You have to escape the string that is passed to RegExp (the backslashes).
var patt= new RegExp('^((0[1-9])|(1[0-2])|[1-9])\\/(\\d{4})$');
Even better, in your case, it's not dynamic, so you should use the literal RegExp instead
var patt = /^((0[1-9])|(1[0-2])|[1-9])\/(\d{4})$/
You should escape your backslashes. To represent \d or even \ you should another backslash behind it (e.g: \\) :
var date = '05/2016'
var patt = new RegExp('^((0[1-9])|(1[0-2])|[1-9])\\/(\\d{4})$');
console.log(patt.test(date));
Try using a pattern like this
patt= /^((0[1-9])|(1[0-2]))\/(\d{4})$/;
This question already has an answer here:
Javascript Regular Expression not matching
(1 answer)
Closed 7 years ago.
I'm trying to replace all occurences of {0}, {1}, {2}, etc in a string with Javascript.
Example string:
var str = "Hello, my name is {0} and I'm {1} years.";
I'm tried the following to construct the regexp:
var regex1 = new RegExp("{" + i + "}", "g")
var regex2 = new RegExp("\{" + i + "\}", "g")
Both attempts throws the error:
Invalid regular expression: /{0}/: Nothing to repeat
I use replace like this:
str.replace(regex, "Inserted string");
Found all kinds of StackOverflow posts with different solutions, but not quite to solve my case.
The string literal "\{" results in the string "{". If you need a backslash in there, you need to escape it:
"\\{"
This will results in the regex \{..\}, which is the correct regex syntax.
Having said that, your approach is more than weird. Using a regex you should do something like this:
var substitues = ['foo', 'bar'];
str = str.replace(/\{(\d+)\}/, function (match, num) {
return substitutes[num];
});
In other words, don't dynamically construct a regex for each value; do one regex which matches all values and lets you substitute them as needed.
This question already has answers here:
Parse query string in JavaScript [duplicate]
(11 answers)
Closed 8 years ago.
So let's say I have this HTML link.
<a id="avId" href="http://www.whatever.com/user=74853380">Link</a>
And I have this JavaScript
av = document.getElementById('avId').getAttribute('href')
Which returns:
"http://www.whatever.com/user=74853380"
How do I extract 74853380 specifically from the resulting string?
There are a couple ways you could do this.
1.) Using substr and indexOf to extract it
var str = "www.something.com/user=123123123";
str.substr(str.indexOf('=') + 1, str.length);
2.) Using regex
var str = var str = "www.something.com/user=123123123";
// You can make this more specific for your query string, hence the '=' and group
str.match(/=(\d+)/)[1];
You could also split on the = character and take the second value in the resulting array. Your best bet is probably regex since it is much more robust. Splitting on a character or using substr and indexOf is likely to fail if your query string becomes more complex. Regex can also capture multiple groups if you need it to.
You can use regular expression:
var exp = /\d+/;
var str = "http://www.whatever.com/user=74853380";
console.log(str.match(exp));
Explanation:
/\d+/ - means "one or more digits"
Another case when you need find more than one number
"http://www.whatever.com/user=74853380/question/123123123"
You can use g flag.
var exp = /\d+/g;
var str = "http://www.whatever.com/user=74853380/question/123123123";
console.log(str.match(exp));
You can play with regular expressions
Well, you could split() it for a one liner answer.
var x = parseInt(av.split("=")[1],10); //convert to int if needed
This question already has answers here:
Converting user input string to regular expression
(14 answers)
Closed 9 years ago.
I am using a very fine JavaScript library called "array-query" by Jacob Wright to do searches in arrays of objects.
One method is regex() where a regular expression can be included in parentheses like this: regex(/[^\w\s]/). If I hardcode the expression as I just showed it works fine. If I put the same expression in a variable first it does not work, like this:
var reg = "/[^\w\s]/";
regex(reg);
I was told
You are putting quotes around your regex, making it a string. Remove the quotes.
Thus
var reg = /[^\w\s]/;
regex(reg);
works fine.
Problem is I need to accept the user input from an textbox as part of the regular expression. For example if the user types in the letter z it needs to get changed to /z/. Even if I type in /z/ the textbox.value returned has the same problem as a var reg = "/z/". If I hardcode var reg = /z/; regex(reg); it works fine.
How to make a input textbox value of "z" into a form that is var reg = z;?
Many many thanks for any help or ideas, hope this isn't too confusing.
You should do
var regex = new RegExp('your regex string');
Basically you can think of
var regex = /pattern/modifiers;
as
var regex = new RegExp(pattern,modifiers);
Read more about it at: MDN or w3schools
var reg = new RegExp("string");
You can do something like this:
var string = $('#input_id').val();
string = string.replace('/', '');
var regexpPattern = '/'+string+'/';
regex(regexpPattern);