p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   Javascript How-To (http://p2p.wrox.com/forumdisplay.php?f=87)
-   -   Replace multiple instances of a String (http://p2p.wrox.com/showthread.php?t=30408)

interrupt June 14th, 2005 06:11 AM

Replace multiple instances of a String

I have been trying to write some smilie code. I have found a function called replace(). Now this works only once within a string and then stops. What I need is to be able to count multiple instances of a string, in this case ":\)", and replace each one with some HTML ("<img src =\"grin.gif\">"). Any ideas anyone?


ChrisScott June 14th, 2005 06:34 AM

Hi interrupt,

You can use a RegExp with replace() & then set it tp apply globally with the g flag, try this:

var myStr = ":\)some:\)other:\)text";
alert(myStr.replace(/:\)/g, "<img src =\"grin.gif\">"));



interrupt June 14th, 2005 06:48 AM

Hi Chris, I did it the long way:

<script language ="javascript">
function addsmile(){

var SmileStr = document.form1.smilebox.value
var thestr = ":\)"
var found = 0;
var thehtml = "<img src =\"grin.gif\">"
var thenewstr

    while (found != -1){
    found = SmileStr.indexOf(thestr, found)

        if (found >-1){
        thenewstr = SmileStr.replace(thestr, thehtml)
        SmileStr = thenewstr


div1.innerHTML = thenewstr

Thanks Anyway


All times are GMT -4. The time now is 05:22 AM.

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.