Can you please help me. How can I add this regex (?<=^|\s):d(?=$|\s) in javascript RegExp?
e.g
regex = new RegExp("?????" , 'g');
I want to replace the emoticon :d, but only if it is surrounded by spaces (or at an end of the string).
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Firstly, as Some1.Kill.The.DJ mentioned, I recommend you use the literal syntax to create the regular expression:
It’s shorter, easier to read and you avoid complications with escape sequences.
The reason why the pattern does not work is that JavaScript does not support lookbehinds (
(?<=...). So you have to find a workaround for that. You won’t get around including that character in your pattern:Since there is no use in capturing anything in your pattern anyway (because
:dis fixed) you are probably only interested in the position of the match. That means, when you find a match, you will have to check whether the first character is a space character (or is not:). If that is the case you have to increment the position by1. If you know that your input string can never start with a space, you can simply increment any found position if it is not0.Note that I simplified your lookahead a bit. That is actually the beauty of lookarounds that you do not have to distinguish between end-of-string and a certain character type. Just use the negative lookahead, and assure that there is no non-space character ahead.
Just for future reference that means you could have simplified your initial pattern to:
(If you were using a regex engine that supports lookbehinds.)
EDIT:
After your comment on the other answer, it’s actually a lot easier to use the workaround. Just write back the captured space-character:
Where
$1refers to what was matched with(^|\s). I.e. if the match was at the beginning of the string$1will be empty, and if there was a space before:d, then$1will contian that space character.