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, '');
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/
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";}
Have you checked the lookaround syntax?
精彩评论