-1

I've a strings like pie and cherrypie.

How do I replace all the occurrences of pie in the strings, that aren't started with pie?

Here's what I've at the moment:

var regexp = new RegExp('pie', 'g');
var string = 'pie';
var string2 = 'cherrypie';
var cap = function(val) {
return val.charAt(0).toUpperCase()+val.slice(1);
}

console.log(string.replace(regexp, cap));
console.log(string2.replace(regexp, cap));

Online demo - http://jsbin.com/ERUpuYuq/1/

Just open a console and you will see two lines:

Pie 
cherryPie 

An expected result is

pie - since it starts with "pie" 
cherryPie 

I've tried to add * symbol at the beginning of my regexp, without any luck.

If I set .pie as my regexp, I get this:

pie 
cherrYpie 

The solution would be a regexp replacement, that will catch all the occurances, that are placed not at the beginnign of the string.

Anyone knows regexp?

Note: cap function shouldn't be modified.

Jasper
  • 5,090
  • 11
  • 34
  • 41

2 Answers2

1

You can add your own function that conditionally calls cap, which you say you can't modify.

var string = 'pie';
var string2 = 'cherrypie';
var string3 = 'piepie';
var cap = function(val) {
    return val.charAt(0).toUpperCase()+val.slice(1);
};
// Capture two arguments: $1 is optional and only set if the string begins with
// something.
var regexp = new RegExp('(.+)?(pie)', 'g');
var capCheck = function($0, $1, $2){
    // If $1 is set, return it plus the capitalised 'pie', otherwise return the
    // original string (no replacement).
    return $1 ? $1 + cap($2) : $0;
};

console.log(string.replace(regexp, capCheck));
// => pie
console.log(string2.replace(regexp, capCheck));
// => cherryPie
console.log(string3.replace(regexp, capCheck));
// => piePie

Since a negative lookbehind assertion isn't available in JavaScript RegExp (I has a sad), this answer gave me the solution needed.

More methods of mimicking lookbehind in JavaScript. The one about reversing the string, using lookahead, then reversing again was quite nice, but it means you can't use lookahead the normal way at the same time.

Community
  • 1
  • 1
Henry Blyth
  • 1,700
  • 1
  • 15
  • 23
0

For example, you can try dot. http://jsbin.com/ERUpuYuq/3/edit?html,js,console,output

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173