【问题标题】:How to cut string based on 3rd occurrence of a character?如何根据字符的第三次出现来剪切字符串?
【发布时间】:2017-08-10 15:08:03
【问题描述】:

假设我有一个类似$foo$bar$baz $5的字符串

我曾尝试通过`$'将字符串拆分为数组,然后删除第一个和第二个元素,然后将数组转换为新字符串。但我想知道是否有更优雅的方式来做到这一点?

【问题讨论】:

  • 我要去掉左边的部分,即$foo$bar$
  • 我曾尝试通过`$'将字符串拆分为数组,然后删除第一个和第二个元素,然后将数组转换为新字符串。但我想知道是否有更优雅的方式来做到这一点。

标签: javascript


【解决方案1】:

您可以删除$ 的前两次出现和一些带有空字符串的文本。

^(\$[^$]+){2}\$    regular expression
^                  start of the string
  \$               search for $ literally
    [^$]           search for any character but not $
        +          quantifier one or more
 (       )         group
          {2}      quantifier for exactly two times
 (       ){2}      get the group only two times
             \$    get the third $

var string = '$foo$bar$baz $5',
    result = string.replace(/^(\$[^$]+){2}\$/, '');

console.log(result);

【讨论】:

  • 你打败了我:D 2 秒差异。
  • 不错的一个!你能补充一些关于魔法是如何工作的解释吗?
  • 对不起,我没有注意到这一点:结果应该是baz $5 而不是$baz $5。你还能在单个正则表达式函数中做到这一点吗?
  • 如何重写以从字符串的开头返回到第 n 次出现,而不是从第 n 次出现返回到结尾?
  • @Benjamin,取match 并且只取结果的第一个索引。
【解决方案2】:

复习一下:-

var str = '$foo$bar$baz $5',
delimiter = '$',
start = 3,
tokens = str.split(delimiter).slice(start),
result = tokens.join(delimiter);
console.log(result); //baz $5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-13
    • 2011-07-26
    • 1970-01-01
    • 2021-01-29
    • 2019-03-01
    • 2014-03-22
    相关资源
    最近更新 更多