Click here to Skip to main content
15,885,869 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
my string is ...
XML
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 :)
Posted

1 solution

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:
XML
<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
 
Share this answer
 
v3
Comments
Aarti Meswania 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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900