Is Str.split(somestring).join(someotherstring) Equivalent To A Replace?
Solution 1:
No, they are not equivalent. Here's one edge case…
Splitting by an empty string returns an array of each character in the original string:
"foo".split('') --> ["f", "o", "o"]
And you might think that an empty regular expression (RegExp('', 'g')
or /(?:)/
) would work the same, especially if you test it out using split:
"foo".split(/(?:)/g) --> ["f", "o", "o"]
However, in the replace method, it works a bit differently. Because it matches every zero-width position in the string, including the zero-width position before the first character and after the last character:
"foo".replace(/(?:)/g, '-') --> "-f-o-o-"
This happens because the split method in a sense 'starts' at first character and 'stops' at the last character, whereas the replace method is allowed to 'start' before the first character and 'stop' after the last. So any regular expression that matches the beginning or end of the string will behave differently.
var testCases = [/(?:)/g, /^/g, /$/g, /\b/g, /\w*/g];
$.each(testCases, function(i, r) {
$("#t").append(
$("<tr>").append(
$("<td>").text(r.toString()),
$("<td>").text("foo bar".split(r).join('-')),
$("<td>").text("foo bar".replace(r, '-'))
)
);
});
* { font-family:monospace; }
table { border-collapse: collapse }
td,th { border:1px solid #999; padding: 3px; }
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><tableid="t"><tr><th>RegExp</th><th>str.split(r).join('-')</th><th>str.replace(r, '-')</th></tr></table>
Solution 2:
You don't have to go very far to see where split().join()
will vary from replace()
. Consider the case where you want to replace all occurrences of the personal pronoun "me" in a string with "myself". split().join()
will replace all occurrences of the alphabetic sequence "me" without regard to usage, so the string "I need some time for me" will become "I need somyself timyself for myself".
However, with an appropriate regex you can capture and replace only the word "me", so your result will be "I need some time for myself".
Solution 3:
TL;DR: No.
Your code is an equivalent of hypothetical string.replaceAll(str,repl)
but not of string.replace(str,repl)
Problem is that string.replace("str","bystr")
replaces only first occurrence of "str". But your code replaces all occurrences.
Post a Comment for "Is Str.split(somestring).join(someotherstring) Equivalent To A Replace?"