2

I have found a short script which finds a line with a certain phrase in it and replaces the whole line with a new line. However I can't work out how to include a variable where it says '#RemoveMe' in the str.replace. (I want to include the variable 'start' which is passed in by the function's trigger, to make --> (/^.start.$/mg, ""))

Any help appreciated...

        var str = 'line1\n'+
          'line2\n'+
          '#RemoveMe line3\n'+
          'line4';

        var test = str.replace(/^.*#RemoveMe.*$/mg, "");

Thanks.

0

1 Answer 1

6

This is a limitation of the inline regular expression notation.

If you use new RegExp() you can pass the expression as a string.

var find = "start";
var regexp = new RegExp("^.*" + find + ".*$", "mg"); // note: no delimiters
str.replace(regexp, "");
Sign up to request clarification or add additional context in comments.

5 Comments

If you need to escape the value (to make sure the user can actually use .'s etc.), you can use PHPJS's version of preg_quote
There is never a (good) reason to allow user input in a regular expression.
@FritsvanCampen negative. user filtering
You don't need regular expressions for text filtering. Anything more complex is probably silly. Wildcards go a long way.
Thank-you, exact answer and extremely quick! :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.