在没有JavaScript方法的字符串中搜索给定的字符串,可以使用以下方法:
function searchInString(str, target) {
let index = 0;
let result = [];
while (index !== -1) {
index = str.indexOf(target, index);
if (index !== -1) {
result.push(index);
index += target.length;
}
}
return result;
}
const originalString = "This is a sample string. Sample is a keyword.";
const searchString = "sample";
const occurrences = searchInString(originalString, searchString);
console.log(occurrences); // Output: [10, 27]
function searchInString(str, target) {
const regex = new RegExp(target, "g");
let result = [];
let match;
while ((match = regex.exec(str)) !== null) {
result.push(match.index);
}
return result;
}
const originalString = "This is a sample string. Sample is a keyword.";
const searchString = "sample";
const occurrences = searchInString(originalString, searchString);
console.log(occurrences); // Output: [10, 27]
以上两种方法都可以在没有JavaScript方法的字符串中搜索给定的字符串。第一种方法使用了indexOf()方法,适用于简单的字符串搜索。第二种方法使用了正则表达式,适用于更复杂的搜索需求,例如支持正则表达式的匹配模式。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云