Kristian
Kristian

Reputation: 1363

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

Upvotes: 16

Views: 47111

Answers (4)

T.J. Crowder
T.J. Crowder

Reputation: 1074989

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.

Upvotes: 25

Keng
Keng

Reputation: 53111

Try this

(/.+){4}

escape as appropriate

Upvotes: 0

Klemen Slavič
Klemen Slavič

Reputation: 19851

What about just splitting the string at slashes and just replacing the values?

var myURL = '/blogs/1/2/all-blogs/', fragments, newURL;
fragments = myURL.split('/');
fragments[1] = 3;
fragments[2] = 8;
fragments[3] = 'some-specific-blog';
newURL = fragments.join('/');

That should return:

'/blogs/3/8/some-specific-blog'

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318568

js> 'www.google.de/blogs/1/2/all-blogs'.replace(/\/blogs\/[^\/]+\/[^\/]+\/[^\/]+\/?/, '');
www.google.de

Upvotes: 1

Related Questions