Evan Plaice
Evan Plaice

Reputation: 14140

Run a RegEx replace on a RegEx in Javascript

I have the regex:

var reValid = /^\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|[^,'\s\\]*(?:\s+[^,'\s\\]+)*)\s*(?:,\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|[^,'\s\\]*(?:\s+[^,'\s\\]+)*)\s*)*$/;

Which validates a CSV file, but I want to be able to modify the delimiter (') with any delimiter.

Is it possible to run a regex replace on a regex?

Example - use a backtick (`) as the delimiter:

var reValid = /^\s*(?:`[^`\\]*(?:\\[\S\s][^`\\]*)*`|[^,`\s\\]*(?:\s+[^,`\s\\]+)*)\s*(?:,\s*(?:`[^`\\]*(?:\\[\S\s][^`\\]*)*`|[^,`\s\\]*(?:\s+[^,`\s\\]+)*)\s*)*$/;

Upvotes: 1

Views: 249

Answers (1)

Paul
Paul

Reputation: 141917

Sure, just use the source property to get the expression as a string, do your replacement, and then create a new RegExp object with the new expression:

var reValid = /^\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|[^,'\s\\]*(?:\s+[^,'\s\\]+)*)\s*(?:,\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|[^,'\s\\]*(?:\s+[^,'\s\\]+)*)\s*)*$/;
reValid = RegExp(reValid.source.replace(/'/g, '`'));

Upvotes: 4

Related Questions