Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
my string is ...
var patt1='/:)/g';
alert(':):):)'.replace(patt1,"*"));
o/p =
:):):)
I want o/p
***

 
How to do?
I am newbie in regex...
 
please help to solve this Smile | :)
Posted 18-Feb-13 2:29am

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Hi Aarti,
 
there are actually two issues with your example.
  1. There is no need for quotes around your pattern literal. Regular Expressions are first class citizens in JavaScript. Look here Regular Expression Cheat Sheet[^] or here W3 Schools RegExp Object[^]
  2. Certain characters in Regular Expressions have a special meaning so they'll have to be escaped if you want the character interpreted literally.
 
Here a fully working example I cooked up for you:
<html>
    <body>
        <h1>Test</h1>
    </body>
    <script type="text/javascript">
        var patt1=/\:\)/g; //Notice how there are no quotes and the : and ) are escaped by a \
        alert(":):):)".replace(patt1,"*"));
    </script>
</html>
 
The alert message shows three asterisks!
 
Regards,
 
— Manfred
  Permalink  
v3
Comments
Aarti Meswania at 19-Feb-13 0:45am
   
working
thanks :)
 
I will Like to share some points I learned
 
1.
write pattern string between slashes and include g or gi at end respectively for case sensitive & case in-sensitive search
e.g. /pattern /gi
 
2.
when want to search '/' in pattern then write '\/' way
e.g. want to search.. ':/' then write... /:\//gi
 
3.
when want to search ')' or '(' in string then also put '\'
e.g. want to search ':)' then /:\)/g

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Zoltán Zörgő 265
1 /\jmot 205
2 CHill60 145
3 Peter Leow 145
4 Sergey Alexandrovich Kryukov 115
0 Sergey Alexandrovich Kryukov 9,353
1 OriginalGriff 6,881
2 Peter Leow 4,577
3 Zoltán Zörgő 4,129
4 Richard MacCutchan 2,882


Advertise | Privacy | Mobile
Web01 | 2.8.150129.1 | Last Updated 18 Feb 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100