use regex to Find and replace instances of @foo, but not @@foo - Javascript String Operation

Javascript examples for String Operation:String Replace

Description

use regex to Find and replace instances of @foo, but not @@foo

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript">
    window.onload=function(){/*from   w w  w .j a  va2  s  . c  o  m*/
var str = 'Hello @website, you can email me at email@@website.com';
var word = 'Patrick';
var result = str.replace(/(^|[^@])(@[a-z0-9]+)/i, '$1' + word).replace(/@{2,}/, '@');
console.log(result);

    }

      </script> 
   </head> 
   <body>  
   </body>
</html>

Related Tutorials