[英]How to Check if a String has the same characters in JavaScript?
Let say I've String假设我有字符串
var str = 'Sumur Bandung'
and和
var x = 'Kecamatan Sumur Bandung'
from str
and x
there are two matching characters Sumur
and Bandung
.从
str
和x
有两个匹配的字符Sumur
和Bandung
。 How can I check that str
has characters that match with x
?如何检查
str
是否有与x
匹配的字符?
let str = "Sumur Bandung";
let x = "Kecamatan Sumur Bandung";
function stringContains(parentString, childString) {
const parentStringSeparator = parentString.split(" ");
return childString
.split(" ")
.every((word) => parentStringSeparator.includes(word));
}
console.log(stringContains(x, str));
If I understand you correctly, this is what you're asking.如果我理解正确,这就是你要问的。 Given a parent string separated by spaces, check if every word of a child string is in the parent string.
给定一个由空格分隔的父字符串,检查子字符串的每个单词是否都在父字符串中。
Edit: This function doesn't take in account word order and splits every string with spaces.编辑:这个 function 不考虑字序,并用空格分割每个字符串。
Edit2: If you're trying to ask whether a child string contains at least one word from a parent string, you should use some instead of every: Edit2:如果您试图询问子字符串是否包含来自父字符串的至少一个单词,您应该使用 some 而不是 every:
let str = "Sumur Bandung";
let x = "Kecamatan Sumur Bandung";
function stringContains(parentString, childString) {
const parentStringSeparator = parentString.split(" ");
return childString
.split(" ")
.some((word) => parentStringSeparator.includes(word));
}
console.log(stringContains(x, str));
You can use " include
", it's the best.你可以使用“
include
”,它是最好的。
var x = 'Kecamatan Sumur Bandung' var str = 'Sumur Bandung' console.log(x.includes(str) || str.includes(x))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.