tags:

views:

225

answers:

1

Do any of the existing JavaScript frameworks have a non-regex replace() function? or has this already been posted on the web somewhere as a one-off function?

For example I want to replace @!#$123=% and I don't want to worry about which characters to escape. Most languages seem to have both methods of doing "replaces". I would like to see this simple thing added.

+7  A: 

i may be misunderstanding your question, but javascript does have a replace()

var string = '@!#$123=%';
var newstring = string.replace('@!#$123=%', 'hi');

edit: (see comments) the 5th edition does seem to have this info in it, although it doesn't show up when i link directly to it. here's the relevant part:

The replace( ) method performs a search-and-replace operation. It takes a regular expression as its first argument and a replacement string as its second argument. It searches the string on which it is called for matches with the specified pattern. If the regular expression has the g flag set, the replace( ) method replaces all matches in the string with the replacement string; otherwise, it replaces only the first match it finds. If the first argument to replace( ) is a string rather than a regular expression, the method searches for that string literally rather than converting it to a regular expression with the RegExp( ) constructor, as search( ) does.

Owen
huh. maybe I was looking at an old version of "Javascript: The Definitive Guide" that only showed the regex example. so I never tried the above code. now I feel really dumb. -10 cool points for me.
tyndall
it happens, i just found a lastIndexOf() method... *sigh*...
Owen
Can someone check the most recent version of "Javascript: The Definitive Guide"? Is this kind of example now included?
tyndall