gobob
gobob

Reputation: 412

node.js replace regex special characters

I'm cleaning up filenames, e.g.

from

zx5-565x372.jpg?642e0d

to

zx5-565x372.jpg

Specifically, I want to remove the ? followed by 6 lowercase alphanumeric characters.

I've tried regex like

modified = original.replace("\?\w{6}", "") 

where \w is same as [a-zA-Z0-9_] and {6} is 6 of the same but with no joy.

Could someone kindly show me the right way?

Upvotes: 0

Views: 1286

Answers (2)

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51400

modified = original.replace("\?\w{6}", "")
                            \_______/

This is just a string literal, it's not matched as a regex pattern.
You are literally replacing the string ?w{6} with an empty string (because escaped ? and w have no special meaning).

Use regex literals instead:

modified = original.replace(/\?\w{6}/, "");

Or just loosen your regex requirements in case the format changes:

modified = original.replace(/\?.*/, "");

Upvotes: 0

Nicolò
Nicolò

Reputation: 1875

You are using a string, not a RegExp.

var modified = original.replace(/\?\w{6}$/, "");

Upvotes: 1

Related Questions