JS 找两个字符串中不同的字符
时间: 2023-12-07 12:05:43 浏览: 17
你可以使用 JavaScript 找到两个字符串中不同的字符。以下是一个示例代码:
```javascript
function findDifferentChars(str1, str2) {
let differentChars = [];
// 将字符串转换为数组
const arr1 = Array.from(str1);
const arr2 = Array.from(str2);
// 比较两个数组的每个元素
for (let i = 0; i < arr1.length; i++) {
if (!arr2.includes(arr1[i]) && !differentChars.includes(arr1[i])) {
differentChars.push(arr1[i]);
}
}
for (let i = 0; i < arr2.length; i++) {
if (!arr1.includes(arr2[i]) && !differentChars.includes(arr2[i])) {
differentChars.push(arr2[i]);
}
}
return differentChars;
}
// 示例用法
const str1 = "abcdefg";
const str2 = "abcxyz";
const result = findDifferentChars(str1, str2);
console.log(result); // 输出: ['d', 'e', 'f', 'g', 'x', 'y', 'z']
```
在上面的示例中,我们使用了两个 for 循环来比较两个字符串的每个字符。如果一个字符在另一个字符串中不存在,并且在不同字符数组中也不存在,我们将其添加到不同字符数组中。最后,返回不同字符数组。
请注意,上述方法将区分大小写。如果您希望不区分大小写,则可以在比较字符时使用 `.toLowerCase()` 或 `.toUpperCase()` 方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)