1

I have a string and a matching pattern like this :

var string = 'stackoverflow Javascript Regex Help';    
var pattern=/(^stackoverflow Javascript)/;

I'm looking for a way to reuse my previous pattern without having to rewrite it again. Shortly, I want to add an additional option at the end of my previous pattern (matching a space before splitting)

var newString=string.split(pattern+/(.\S*)/);
alert(newString); //Regex Help

But this doesn't work. Is there a way I can accomplish this ?

Thank you for your hep.

4
  • 1
    To reuse regex, you can use RegExp constructor syntax. Commented Mar 8, 2016 at 13:33
  • 1
    "I'm looking for a way to reuse my previous pattern without having to rewrite it again." — But why? This smells of completely unfounded premature optimization. Commented Mar 8, 2016 at 13:34
  • 1
    Related: How do you pass a variable to a Regular Expression JavaScript? Commented Mar 8, 2016 at 13:38
  • 1
    Just create the regular expressions as you need them. Extending the functionality of existing regular expressions is generally unnecessary. Commented Mar 8, 2016 at 14:23

2 Answers 2

3

You can use RegExp to build a regular expression from a string:

var common_pattern = "(^stackoverflow Javascript)";
var extra_pattern = "(.\\S*)"; // need to escape the escape character because the pattern is now a string
var regexp = new RegExp(common_pattern + extra_pattern);

var newString = string.split(regexp);
Sign up to request clarification or add additional context in comments.

6 Comments

Note that common_pattern/pattern is a regex in Q. and string here. This is not actually reuse of a regex.
@Marcin what do you mean? I copied your regular expressions, I didn't change them.
"(.\S*)" becomes "(.S*)" so that can't be correct. What is your expected output?
I don't understand what you're trying to do. Can you give other example input and output?
Right .. so how about: "stackoverflow Javascript Hip Hop Hoop".match(/^stackoverflow Javascript ?(.+)$/) otuput: ["stackoverflow Javascript Hip Hop Hoop", "Hip Hop Hoop"]. This will also optionally match the space.
|
0

If you truly want to reuse the pattern it could be done with RegExp's toString.

Se example at JSFiddle here.

This example first splits the string using the digit 1. Then adds the digit 2 to the patter to split at 12.

Snip:

var newPattern = new RegExp(pattern.toString().slice(1,-1) + '2');

Regards

Edit: Updated example to properly handle modifiers.

1 Comment

NB! As Halcyon I'm having trouble figuring out exactly what you want, so this is simply a proof of concept. It's not an exact answer to your specific example/problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.