使用与分割相同的分隔符连接字符串 [英] Join the string with same separator used to split

查看:56
本文介绍了使用与分割相同的分隔符连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,需要使用正则表达式进行拆分才能进行一些修改.

I have a string that need to be split with a regular expression for applying some modifications.

例如:

const str = "Hello+Beautiful#World";
const splited = str.split(/[\+#]/)

// ["Hello", "Beautiful", "World"]

现在,该字符串已使用 + #进行了拆分.现在说,对数组中的项目进行一些修改之后,我必须使用与拆分相同的分隔符来加入数组,因此字符 + #必须和以前一样.

Now the string has been split with + or #. Now say after applying some modification to the items in the array, I have to join the array using the same separator that used to split, so the character + and # has to be in the same position as before.

例如:如果我应用了一些修改字符串并加入了.那应该是.

eg: if i applied some modification string and joined. Then it should be.

Hello001+Beutiful002#World003

我该怎么做?

推荐答案

将模式放置在捕获组中时, split 会将匹配的定界符作为偶数数组项返回.因此,您所需要做的就是修改奇数项:

When you place a pattern inside a capturing group, split will return the matched delimiters as even array items. So, all you need to do is modify the odd items:

var counter=1;
var str = "Hello+Beautiful#World";
console.log(
  str.split(/([+#])/).map(function(el, index){
    return el + (index % 2 === 0 ? (counter++ + "").padStart(3, '0') : '');
  }).join("")
);

这篇关于使用与分割相同的分隔符连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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