如何在JavaScript中串联两个没有重复的字符串 [英] How to concatenate two strings without duplicates in JavaScript

查看:44
本文介绍了如何在JavaScript中串联两个没有重复的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个字符串如下:

var str1 = "5YRS,AC,ALAR";
var str2 = "MON,5YRS,TRAU";

我想将这两个字符串合并为一个字符串,并删除其中的重复项.我尝试了以下方法:

I want to merge these two strings into one string and to remove duplicates in this. I tried the below method:

var main_str = str1.concat(str2) //result: "5YRS,AC,ALARMON,5YRS,TRAU"

我得到的结果在最后被合并,并且如果我动态推送任何字符串,它不会显示期望的结果.是否有任何新的ES6实现可获取同时检查null检查并返回唯一字符串值的方法.

Result which i got is getting merged at on end and if i push any string dynamically it is not showing the desired result. Is there any new ES6 implementation to get a method which checks both null check and return unique string values.

推荐答案

您可以将两个字符串与一个数组连接在一起,然后拆分这些值以从

You could join the two strings with an array and then split the values for getting unique results from a Set.

var str1 = "5YRS,AC,ALAR",
    str2 = "MON,5YRS,TRAU",
    joined = Array.from(new Set([str1, str2].join(',').split(','))).join(',');

console.log(joined);

这篇关于如何在JavaScript中串联两个没有重复的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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