wyc
wyc

Reputation: 55263

How do I replace only a portion of the following regex (JavaScript)?

I'm learning regexs and file saving. As exercise, I wanted to turn every func in a file into function:

data.replace(/func\((.*)\)/g, 'function')

The problem is that the funcs in the file now end up like this:

var thisfunc = function {

}

Instead of this:

var thisfunc = function() {

}

How should I do it so that the regex only replaces the func keyword?

EDIT:

input:

fs.readFile(filename, 'utf8', func(err, data) {
  if (err) throw err
  console.log('OK: ' + filename)
  var newData = data.replace(/func\((.*)\)/g, 'function')
  console.log(newData)
})

var thisfunc = func() {

}

Upvotes: 0

Views: 41

Answers (3)

Aprillion
Aprillion

Reputation: 22324

match and replace only the opening parenthesis,
especially if those can be nested like in func(a, func(b)):

data.replace(/func\(/g, 'function(')

Note: in environments where replacement string needs escape sequence for (, use function\(, this is not necessary in javascript

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174696

Here you actually need a positive lookahead assertion. And you don't need to use capturing group.

data.replace(/func(?=\(.*\))/g, 'function')

OR

.*? here will do a non-greedy match of any character zero or more times.

data.replace(/func(?=\(.*?\))/g, 'function')

(?=\(.*?\)) Asserts that the keyword func must be followed by pair of parenthesis which may or may-not contain arguments.

Upvotes: 1

Bergi
Bergi

Reputation: 664346

Your regex is also matching the arguments (in the parenthesis), and the whole match will be replaced by only function. You can either:

  • exclude the arguments from the matching, e.g. with lookahead

    data.replace(/func(?=\((.*)\))/g, 'function')
    
  • or "re"insert them in the replacement string:

    data.replace(/func\((.*)\)/g, 'function($1)')
    

Upvotes: 1

Related Questions