Better ways to replace text - performance
Are there better more performant ways to replace text then using the regex code below, specially if text is large and constantly accessed by different users. I understand performance gains may be negligible, but i'm wondering if there are better way to do it. This is what i use to replace foo with foonew
str.repla开发者_如何学运维ce(/foo/gi, 'foonew')
Update: Text data gets retrieved from database into a textarea holder before doing word replacement. I then access textarea value, replace the words, then append updated text to body
Well, patric dw's comment is probably the right answer here. But let's suppose for the sake of argument that you really had to replace a random substring in some larger string, and there was no simple trick to avoid it. Here are three possibilities:
If you are replacing a string with one of smaller length, then you can just shift the characters to the right over it to make up the difference. This avoids reallocating the string.
If the replacement is the same size, you can just do it in place with no copying.
Finally, if it is larger, you can do the string replacement lazily. Just store an object with the string you are substituting and the start/end of the segment that was replaced. This way you can avoid copying. Of course this is much more complicated than just doing the string replacement by hand, so I would probably avoid it unless the performance considerations were really dire.
Text data gets retrieved from database into a textarea holder before doing word replacement. I then access textarea value, replace the words, then append updated text to body.
The most effiecient (and most secure) way to do this is to replace the words, server-side, before ever sending the data.
Then your JS (which the user can modify!) has to do nothing but display the information.
Depending on traffic/volume, it may pay to even have sanitized versions of the text, stored in the database.
精彩评论