David G
David G

Reputation: 96810

RegExp help: How do I find a match for a character that has a particular character coming before it?

I'm actually trying to delete every space in a small function statement excepted if the word "function" or "return" comes before it. This is what I tried but to no avail:

function hi() {
    return "Hello";
}
hi.toString().replace(/\b\s+?=(return|function)/g, '');

Upvotes: 0

Views: 60

Answers (3)

dfsq
dfsq

Reputation: 193261

Well I have pretty funny solution.

// Helper method reverse
String.prototype.reverse = function() {
    return this.split('').reverse().join('');
};

hi.toString().reverse().replace(/(\s+(?!nruter|noitcnuf))/g, '').reverse();

In Javascript we can't use negative lookbehind, but we can reverse the string and use negative lookahead, and then reverse string back! For your function it will give:

function hi(){return "Hello";}

Upvotes: 2

Kashyap
Kashyap

Reputation: 17441

Have you checked the lookaround syntax?

Upvotes: 0

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99911

There is no lookbehind in javascript regex, but this should do the trick:

hi.toString().replace(/(return|function)?\s/g, function(match) {
    if (match.length > 1) return match;
    else return '';
});

This matches single spaces, eventually preceeded by function or return.

If the match is a single character, we replace it by an empty string. Else, we do not replace it.

Try it here: http://jsfiddle.net/ebY5w/2/

Upvotes: 3

Related Questions