Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript replace regex wildcard

I have a string which I need to run a replace.

string = replace('/blogs/1/2/all-blogs/','');

The values 1, 2 and all-blogs can change. Is it possible to make them wildcards?

Thanks in advance,

Regards

like image 993
Kristian Avatar asked Nov 19 '10 13:11

Kristian


1 Answers

You can use .* as a placeholder for "zero or more of any character here" or .+ for "one or more of any character here". I'm not 100% sure exactly what you're trying to do, but for instance:

var str = "/blogs/1/2/all-blogs/";
str = str.replace(/\/blogs\/.+\/.+\/.+\//, '');
alert(str); // Alerts "", the string is now blank

But if there's more after or before it:

str = "foo/blogs/1/2/all-blogs/bar";
str = str.replace(/\/blogs\/.+\/.+\/.+\//, '');
alert(str); // Alerts "foobar"

Live example

Note that in both of the above, only the first match will be replaced. If you wanted to replace all matches, add a g like this:

str = str.replace(/\/blogs\/.+\/.+\/.+\//g, '');
//                                       ^-- here

You can read up on JavaScript's regular expressions on MDC.

like image 169
T.J. Crowder Avatar answered Sep 20 '22 14:09

T.J. Crowder