- String.split( "" ) - String to character array.
- Array.join( "" ) - Character array to string.
Ok, let's take a look at some code. In the following demo, I am updating the core String prototype. That means that our splice() method will be available to all string instances, now and in the future (since they all extend the same String.prototype object):
As you can see, the workflow is actually quite simple:
- Convert string to character array.
- Perform array-based splicing.
- Convert character array back to string.
When we run the above code, we get the following console output:
New message: Katie is an amazing person!.
As you can see, the existing substring "sort of cool" was deleted and the new substring "an amazing person!" was inserted. While this operation is being executed, our base data structure becomes an array of character values. And yet, the value we are inserting is a string; this mixing of "data types" doesn't matter because when we join() the array of characters back together, it all gets flattened into one string value.
Want to use code from this post? Check out the license.
nice article ben! any time you're augmenting the built-ins, it's a good idea to at least check for the presence of the property before adding it, something like:
or you can always try to default to the native's existing property (if you're polyfilling, for example with Array.forEach or Object.keys),thereby only creating it if necessary
as always, keep up the good work!
@Ben, totally tangential: Just watched the movie Splice. Similar topic to an otherwise-stale genre (The Host, Mimic, Species, etc), but with a critter that can be as lovable as Gizmo.
I've seen Splice. I actually really liked it. I have to admit, it was kind of a "hot" movie - though the ending was a bit strange. My friend wanted to take her kids to see it; I advised against it :)
If you mean what I think you mean about "a bit strange", that was foreshadowed twice. Not that foreshadowing made it any less strange. Without giving away any spoilers, I think they must've started with the some of same genetic material as Ginger.
Anyway, it's currently showing on Cinemax if your friend wants to watch it without her kids. Here are some trailers:
Oh, and I liked it to. Inventive.
Yeah, it was definitely foreshadowed with those slug creatures (or whatever the heck they were).
man you rock!!!!!!!
Thanks my man!