str.split(someString).join(someOtherString) 等价于替换吗? [英] Is str.split(someString).join(someOtherString) equivalent to a replace?

查看:22
本文介绍了str.split(someString).join(someOtherString) 等价于替换吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道,例如,"This is a test".split("i").join("j") 具有替换 的每个实例的效果i""j".我很好奇拆分和加入的过程是否完全等价使用正则表达式替换,或者是否有任何极端情况,对于给定的字符串 str1, str2str3 我们有

So I know that, for example, "This is a test".split("i").join("j") has the effect of replacing every instance of "i" with "j". I'm curious about whether that procedure of splitting and joining is exactly equivalent to using a Regex replace or whether there are any corner cases where for given strings str1, str2 and str3 we have

str1.split(str2).join(str3) != str1.replace(/str2/g,str3)

为了澄清起见,str1.replace(/str2/g,str3) 我的意思是一个假设的 str1.replaceAll(str2,str3) 替换所有出现的str2str3

For clarification, by str1.replace(/str2/g,str3) I mean a hypothetical str1.replaceAll(str2,str3) that replaces all occurrences of str2 with str3

推荐答案

不,它们不等同.这是一种边缘情况…

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"]

并且您可能认为空的正则表达式(RegExp('', 'g')/(?:)/)也能正常工作,尤其是如果您使用 split 进行测试:

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-"

发生这种情况是因为 split 方法从某种意义上说从第一个字符开始"并在最后一个字符处停止",而 replace 方法允许在第一个字符和 ' 之前 停止'最后.因此,任何匹配字符串开头或结尾的正则表达式的行为都会有所不同.

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; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="t">
  <tr>
    <th>RegExp</th>
    <th>str.split(r).join('-')</th>
    <th>str.replace(r, '-')</th>
  </tr>
</table>

这篇关于str.split(someString).join(someOtherString) 等价于替换吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆