两个字符串中的字符相交 [英] Intersection of characters in two strings

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

问题描述

我有一个带有字符串的对象.

filteredStrings = {search:'1234', select:'1245'}

我想回来

'124'

我知道我可以将其转换为数组,然后遍历每个值并测试该值是否在另一个字符串的内部,但是我正在寻找一种更简便的方法.最好搭配Lodash.

我已经找到_.intersection(Array,Array),但这仅适用于Arrays.

https://lodash.com/docs#intersection

我希望能够做到这一点而不必将对象转换为数组,然后遍历每个值,因为这将潜在地保存大量信息,并且我希望它尽快运行. /p>

感谢您的帮助.

解决方案

将字符串之一(search)转换为RegExp字符集.将RegExp与 String#match 一起使用另一个字符串(select).

注意:与lodash的交集不同,结果字符不是唯一的,因此例如4可以出现两次.

 var filteredStrings = {search:'1234', select:'124561234'}

var result = (filteredStrings.select.match(new RegExp('[' + filteredStrings.search + ']', 'g')) || []).join('');

console.log(result); 

I have an object with strings in it.

filteredStrings = {search:'1234', select:'1245'}

I want to return

'124'

I know that I can turn it into an array and then loop through each value and test if that value in inside of the other string, but I'm looking for an easier way to do this. Preferably with Lodash.

I've found _.intersection(Array,Array) but this only works with Arrays.

https://lodash.com/docs#intersection

I want to be able to do this without having to convert the object to an array and then loop through each value because this is going to be potentially holding a lot of information and I want it to work as quickly as possible.

Thank you for you help.

解决方案

Convert one of the strings (search) to a RegExp character set. Use the RegExp with String#match on the other string (select).

Note: Unlike lodash's intersection, the result characters are not unique, so for example 4 can appear twice.

var filteredStrings = {search:'1234', select:'124561234'}

var result = (filteredStrings.select.match(new RegExp('[' + filteredStrings.search + ']', 'g')) || []).join('');

console.log(result);

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

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