Split string once in javascript?

前端 未结 13 1009
南笙
南笙 2020-11-29 03:23

How can I split a string only once, i.e. make 1|Ceci n\'est pas une pipe: | Oui parse to: [\"1\", \"Ceci n\'est pas une pipe: | Oui\"]?

The

13条回答
  •  时光说笑
    2020-11-29 03:36

    An alternate, short approach, besides the goods ones elsewhere, is to use replace()'s limit to your advantage.

    var str = "1|Ceci n'est pas une pipe: | Oui";
    str.replace("|", "aUniquePhraseToSaySplitMe").split("aUniquePhraseToSaySplitMe");
    

    As @sreservoir points out in the comments, the unique phrase must be truly unique--it cannot be in the source you're running this split over, or you'll get the string split into more pieces than you want. An unprintable character, as he says, may do if you're running this against user input (i.e., typed in a browser).

提交回复
热议问题