Forum Moderators: open

Message Too Old, No Replies

Array search+replace

         

adni18

7:43 pm on Apr 14, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I came across this JS jewel [kevin.vanzonneveld.net] the other day and found it quite interesting, so I decided to contribute to the code a little and added a functionality I've always wanted in javascript: array searching and replacing.

If you take a look at str_replace, you'll see the code, which is quite useful if you're trying to replace multiple things with multiple things which may contain other things that could be misconstrued as one of the original things by the interpreter (confusing, I know ;-)). There's an example in the code, but I'd just thought I'd throw that out there. It's especially useful for replacing text with HTML image tags, like one might for emoticons.

adni18

1:11 am on Apr 15, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



str_replace(new Array("banned", "word"), new Array("[banned word!]", "WORD"), "This word is banned!")

compare to

new String("This word is banned!").replace(/banned/g, "[banned word!]").replace(/word/g, "WORD")

C'est très useful ;-)

httpwebwitch

1:16 pm on Apr 15, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



adni18, this is fantastic! For PHP coders who are constantly fudging syntax between PHP and JS (myself included), that library is going to be very useful. Their str_replace is excellent.

I'm a little worried that the PHPJS library doesn't tuck all its functions into an object namespace - I wonder if it will conflict with built-in prototypes, or other libraries? I'm already using one kit that hijacks the root scope (it's Mootools - but that's one of the reasons I like using it). I don't mind adding another, as long as the two can play nicely together.

Good find! thanks!

adni18

8:41 pm on Apr 15, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Actually, there is a namespaced version ;-)

Clicky [kevin.vanzonneveld.net]

coopster

1:15 pm on Apr 16, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Wasn't it the PHP Smarty template that first had all these PHP/JS named functions written/embedded in it? No, I just looked and didn't see it right off ... but I remember seeing PHP functions rewritten in JS in a package before, I just cannot recall where that was ...