Javascript RegEx global string search for underscore character(_) - javascript

I am horrible with RegEx and I have been using this online tester for some time now and still can not find what I need.
So I have the string "2011_G-20_Cannes_summit". I want to replace all the underscores (_) with spaces.
So I want something like this:
var str = "2011_G-20_Cannes_summit";
str.replace(/_/g," "); or str.replace(/\_/g);
Though neither is working...
What am I missing?

That works fine. The replace method doesn't modify the existing string, it creates a new one. This will do what you want:
var str = "2011_G-20_Cannes_summit";
str = str.replace(/_/g," ");

Related

Remove first folder in string

I have a folder path that always starts with a certain string which I want to remove. Let's say it looks like this:
my-bucket/2929023/32822323/file.jpg
I want it to look like this:
2929023/32822323/file.jpg
How would I do that? Thanks!
Using the functions substring and indexOf from String.prototype.
var str = "my-bucket/2929023/32822323/file.jpg";
console.log(str.substring(str.indexOf('/') + 1))
You could use a simple replace method if the string is only present once;
var string = "my-bucket/2929023/32822323/file.jpg";
var revisedString = string.replace('my-bucket/', '');
console.log(revisedString);
However, you're also able to use a Regex (regular expression) to remove it as well, something like;
var string = "my-bucket/2929023/32822323/file.jpg";
console.log(string.replace(/^my-bucket\//, ''));
Use a regex to rip the first one out. No substrings necessary.
var myString= "my-bucket/2929023/32822323/file.jpg";
myString = myString.replace(/^.+?[/]/, '');

Firefox Extension How to pass string type variable into javascript replace regex parameter?

I've been working on firefox extension for several days now and there is one thing I can't solve.
I generate a list of regex and I wanted to pass that string into replace function in javascript (in the regex parameters). Here is the example of the string:
/(https?:\/\/(www\.)?rapidgator\.net\b([-a-zA-Z0-9#:%_\+.~#?&//=]*))/g
/(https?:\/\/(www\.)?ul\.to\b([-a-zA-Z0-9#:%_\+.~#?&//=]*))/g
/(https?:\/\/(www\.)?uploadable\.ch\b([-a-zA-Z0-9#:%_\+.~#?&//=]*))/g
/(https?:\/\/(www\.)?180upload\.com\b([-a-zA-Z0-9#:%_\+.~#?&//=]*))/g
For a convenient way, lets make it this way. I managed to get the file and get the first line of the string and assign it into a variable:
var rapidgator = "/(https?:\/\/(www\.)?rapidgator\.net\b([-a-zA-Z0-9#:%_\+.~#?&//=]*))/g";
I want the string to be a "replace parameter" like this:
var rep = rep.replace(rapidgator,"<a href='$1'>$1</a>");
But I cant get that work.
I've been trying to use RegExp object and that didn't work to.
var rapidgator = new RegExp("(https?:\/\/(www\.)?rapidgator\.net\b([-a-zA-Z0-9#:%_\+.~#?&//=]*))", "g");
How to make that work? Thank you for your advice :)
If you can get the regex, why not let it remain a regex literal?
var rapidgator = /(https?:\/\/(www\.)?rapidgator\.net\b([-a-zA-Z0-9#:%_\+.~#?&//=]*))/g;
If you want to make it through RegExp constructor, make sure you escape \ with another backslash and you don't need delimiters and the second argument takes the flags.
As in
var rapidgator = new RegExp("(https?:\\/\\/(www\\.)?rapidgator\\.net\\b([-a-zA-Z0-9#:%_\+.~#?&//=]*))","g")
You need to escape the backslash one more time when passing your regex within double quotes.
var rapidgator = new RegExp("(https?://(www\\.)?rapidgator\\.net\\b([-a-zA-Z0-9#:%_\\\\+.~#?&/=]*))", "g");
And also to match a backslash, you need to escape it exactly three times.

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.

Javascript regex grouping

I am trying to create a regular expression that would easily replace an input name such as "holes[0][shots][0][unit]" to "holes[0][shots]1[unit]". I'm basically cloning a HTML input and would like to make sure its position is incremented.
I got my regex built and working correctly using this (awesome) tool : http://gskinner.com/RegExr/
Here is my current regex :
(.*\[shots\]\[)([0-9]+)(\].*\])
and I am using a replace such as :
$12$3
this transforms "holes[0][shots][0][unit]" into "holes[0][shots][2][unit]". This is exactly want I want. However, when I try this in javascript (http://jsfiddle.net/PH2Rh/) :
var str = "holes[0][shots][0][units]";
var reg =new RegExp("(.*\[shots\]\[)([0-9]+)(\].*\])", "g");
console.log(str.replace(​reg,'$1'));​​​​​​​​​​​​​​​​​​​​​​​​
I get the following output : holes[0
I don't understand how my first group is supposed to represent "holes[0", since I included the whole [shots][ part in it.
I appreciate any inputs on this. THank you.
In strings, a single \ is not interpreted as a Regex-escaping character. To escape the bracket within string literals, you have to use two backslashes, \\:
var reg = new RegExp("(.*\\[shots\\]\\[)([0-9]+)(\\].*\\])", "g");
A preferable solution is to use RegEx literals:
var reg = /(.*\[shots\]\[)([0-9]+)(\].*\])/g;
Looks like, this works:
var str = "holes[0][shots][0][units]";
var reg = /(.*\[shots\]\[)([0-9]+)(\].*\])/;
console.log(str.replace(​reg,'$1'));​​​​​​​​​​​​​​​​​​​​​​​​

Passing regex modifier options to RegExp object

I am trying to create something similar to this:
var regexp_loc = /e/i;
except I want the regexp to be dependent on a string, so I tried to use new RegExp but I couldn't get what i wanted.
Basically I want the e in the above regexp to be a string variable but I fail with the syntax.
I tried something like this:
var keyword = "something";
var test_regexp = new RegExp("/" + keyword + "/i");
Basically I want to search for a sub string in a larger string then replace the string with some other string, case insensitive.
regards,
alexander
You need to pass the second parameter:
var r = new RegExp(keyword, "i");
You will also need to escape any special characters in the string to prevent regex injection attacks.
You should also remember to watch out for escape characters within a string...
For example if you wished to detect for a single number \d{1} and you did this...
var pattern = "\d{1}";
var re = new RegExp(pattern);
re.exec("1"); // fail! :(
that would fail as the initial \ is an escape character, you would need to "escape the escape", like so...
var pattern = "\\d{1}" // <-- spot the extra '\'
var re = new RegExp(pattern);
re.exec("1"); // success! :D
When using the RegExp constructor, you don't need the slashes like you do when using a regexp literal. So:
new RegExp(keyword, "i");
Note that you pass in the flags in the second parameter. See here for more info.
Want to share an example here:
I want to replace a string like: hi[var1][var2] to hi[newVar][var2].
and var1 are dynamic generated in the page.
so I had to use:
var regex = new RegExp("\\\\["+var1+"\\\\]",'ig');
mystring.replace(regex,'[newVar]');
This works pretty good to me. in case anyone need this like me.
The reason I have to go with [] is var1 might be a very easy pattern itself, adding the [] would be much accurate.
var keyword = "something";
var test_regexp = new RegExp(something,"i");
You need to convert RegExp, you actually can create a simple function to do it for you:
function toReg(str) {
if(!str || typeof str !== "string") {
return;
}
return new RegExp(str, "i");
}
and call it like:
toReg("something")

Categories