How to use a variable value as a regex pattern - javascript

I am desperate - I don't see what I'm doing wrong. I try to replace all occurrences of '8969' but I always get the original string (no matter whether tmp is a string or an int). Maybe it's already too late, maybe I'm blind, ...
var tmp = "8969";
alert("8969_8969".replace(/tmp/g, "99"));
Can someone help me out?

The / characters are the container for a regular expression in this case. 'tmp' is therefore not used as a variable, but as a literal string.
var tmp = /8969/g;
alert("8969_8969".replace(tmp, "99"));

alert("8969_8969".replace(/8969/g, "99"));
or
var tmp = "8969"
alert("8969_8969".replace(new RegExp(tmp,"g"), "99"));
Live DEMO

Dynamic way of handling a regex:
var nRegExp = new RegExp("8969", 'g');
alert("8969_8969".replace(nRegExp, "99"));

/tmp/g. This is a regex looking for the phrase "tmp". You need to use new RegExp to make a dynamic regex.
alert("8969_8969".replace(new RegExp(tmp,'g'), "99"));

Javascript doesn't support that usage of tmp, it will try to use 'tmp' literally, as a regex pattern.
"8969_8969".replace(new RegExp(tmp,'g'), "99")

Related

Doesn't get JavaScript RegEx to work

Need help getting the following JavaScript RegEx case insensitive:
^(ABCDE)\d{5}$
I have tried /i but it doesn't work:
^(ABCDE)\d{5}$/i
Where should I place /i to get it to work?
Thanks in advance.
When you have a literal regex notation, just use /.../:
var re = /^(ABCDE)\d{5}$/i;
If you use a RegExp constructor:
var re = RegExp("^(ABCDE)[0-9]{5}$", "i");
However, the literal notation is preferable here since the pattern is constant, known from the beginning, and no variables are used to build it dynamically. Note that if you were to use \d in the RegExp constructor, you'd have to double the backslashes:
var re = RegExp("^(ABCDE)\\d{5}$", "i");
Try to write it this way :
var regex = /^(ABCDE)\d{5}$/i;
It needs the first / or you can also use
var regex = new RegExp('^(ABCDE)\\d{5}$', 'i');
Then if you try in a console this it should work (online testers can add other issue, just try directly on your code) :
regex.test('ABCDE12345') // true
regex.test('abcde12345') // true
Test on Regex101 : https://regex101.com/r/zR5yR0/1

RegEx Ignore Case

I've been trying to create a regex which would ignore the casing.
This is the regex i am trying to use:
/^[A-Za-z0-9._+\-\']+#+test.com$/;
So basically i would want to match any of these
abc#Test.com
abc#TEST.com
abc#teSt.com
I tried this, but it doesn't work:
/^[A-Za-z0-9._+\-\']+#+(?i)+test.com$/;
I read somewhere about the use of (?i), but couldn't find any examples which show their usage in regex to ignore casing.
Thoughts anyone ? Thanks a lot in advance.
Flags go at the end.
/regex/i
i is for case-Insensitive (or ignore-case)
For anyone else who arrives here looking for this, if you've got code that is using the RegExp constructor you can also do this by specifying flags as a second argument:
new RegExp(pattern[, flags])
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp
For example:
var pattern = /^[A-Za-z0-9._+\-\']+#+test.com$/;
var regExp = new RegExp(pattern, "i");
Simple and straightforward, use following regex expression.
(?i)^[A-Za-z0-9._\-\']+#test.com$

jQuery / Javascript replace multiple occurences not working

I'm trying to replace multiple occurrences of a string and nothing seems to be working for me. In my browser or even when testing online. Where am I going wrong?
str = '[{name}] is happy today as data-name="[{name}]" won the match today. [{name}] made 100 runs.';
str = str.replace('/[{name}]/gi','John');
console.log(str);
http://jsfiddle.net/SXTd4/
I got that example from here, and that too wont work.
You must not quote regexes, the correct notation would be:
str = str.replace(/\[{name}\]/gi,'John');
Also, you have to escape the [], because otherwise the content inside is treated as character class.
Updating your fiddle accordingly makes it work.
There are two ways declaring regexes:
// literal notation - the preferred option
var re = /regex here/;
// via constructor
var re = new Regexp('regex here');
You should not put your regex in quotes and you need to escape []
Simply use
str = str.replace(/\[{name}\]/gi,'John');
DEMO
While there are plenty of regex answers here is another way:
str = str.split('[{name}]').join('John');
The characters [ ] { } should be escaped in your regular expression.

Regular Expression - Search and Replace

I'm new to regular expression and have come across a problem.
I want to do a search and replace on a string.
Search for an instance of -- and ' and replace it with - and `, respectively.
Example
Current String: Hi'yo every--body!
Replaced String: Hi`yo every-body!
Any help would greatly be appreciated!
You need.
"Hi'yo every--body!".replace(/--/g, '-').replace(/'/,'`')
Make a function
function andrew_styler(s){return s.replace(/--/g, '-').replace(/'/,'`');}
If you want just replace -- with - use the simplest regexp:
var str = "Hi'yo every--body!";
str = str.replace(/--/g, '-');
The flag g turns the global search on, so that pattern replace all occurances.
#dfsq is correct, regexp is overkill for a couple of simple replaces but for reference.
var s = "Hi'yo every--body!";
s = s.replace(/'/g, "`").replace(/\-{2}/g, "-");

Help with a regular expression to capture numbers

I need to capture the price out of the following string:
Price: 30.
I need the 30 here, so I figured I'd use the following regex:
([0-9]+)$
This works in Rubular, but it returns null when I try it in my javascript.
console.log(values[1]);
// Price: 100
var price = values[1].match('/([0-9]+)$/g');
// null
Any ideas? Thanks in advance
Try this:
var price = values[1].match(/([0-9]+)$/g);
JavaScript supports RegExp literals, you don't need quotes and delimiters.
.match(/\d+$/) should behave the same, by the way.
See also: MDN - Creating a Regular Expression
Keep in mind there are simpler ways of getting this data. For example:
var tokens = values[1].split(': ');
var price = tokens[1];
You can also split by a single space, and probably want to add some validation.
Why don't you use this?
var matches = a.match(/\d+/);
then you can consume the first element (or last)
my suggestion is to avoid using $ in the end because there might be a space in the end.
This also works:
var price = values[1].match('([0-9]+)$');
It appears that you escaped the open-perens and therefore the regex is looking for "(90".
You don't need to put quotes around the regular expression in JavaScript.

Categories