JS string.split() 不删除分隔符 [英] JS string.split() without removing the delimiters

查看:49
本文介绍了JS string.split() 不删除分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不删除分隔符的情况下拆分字符串?

How can I split a string without removing the delimiters?

假设我有一个字符串:var string = "abcdeabcde";

当我这样做时var newstring = string.split("d"),我得到这样的结果:

When I do var newstring = string.split("d"), I get something like this:

["abc","eabc","e"]

但我想得到这个:

["abc","d","eabc","d","e"]

当我尝试执行split2"函数时,我陷入了 splice() 和索引以及this"与that"之间的纠缠……啊!帮助!:D

When I tried to do my "split2" function, I got all entangled in splice() and indexes and "this" vs "that" and ... aargh! Help! :D

推荐答案

试试这个:

  1. 将所有d"实例替换为,d"
  2. 按,"分割

var string = "abcdeabcde";
var newstringreplaced = string.replace(/d/gi, ",d");
var newstring = newstringreplaced.split(",");
return newstring;

希望这会有所帮助.

这篇关于JS string.split() 不删除分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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