gpt4 book ai didi

javascript - 从段落中搜索文本 - Javascript?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:46:20 25 4
gpt4 key购买 nike

我写了下面的代码来从一个段落中搜索我的名字,

 /*jshint multistr:true */

text = "Blah blah blah blah blah blah Elic \
blah blah blah Eric blah blah Eric blah blah \
blah blah blah blah blah Eric";

var myName = "Eric";
var hits = [];
var l=0;
var count=0;


// Look for "E" in the text
for(var i = 0; i < text.length; i++) {
if (text[i] === "E") {

for(var j = i; j < (myName.length + i); j++) {
for(var k =1; k < 4; k++) {
if(text[i+k] === myName[k]){

hits.push(text[j]);
}
else {
break;
}

}
}

}
}



if (hits.length === 0) {
console.log("Your name wasn't found!");
} else {
console.log(hits);
}

但是输出是这样的 [ 'E',
'E',
'E',
'r',
'r',
'r',
'我',
'我',
'我',
'C',
'C',
'C',
'E',
'E',
'E',
'r',
'r',
'r',
'我',
'我',
'我',
'C',
'C',
'C',
'E',
'E',
'E',
'r',
'r',
'r',
'我',
'我',
'我',
'C',
'C',
'c']

我确定这是因为第 3 个 for 循环,请给出一些建议来微调这段代码,以便输出像这样,

[ 'E', 'r', 'i', 'c', 'E', 'r', 'i', 'c', 'E', 'r', 'i', 'c', 'E', 'r', 'i', 'c' ]

提前致谢。

最佳答案

1

var res = text.match(new RegExp(myName, 'g')).join('').split('');

2

var text = "Blah blah blah blah blah blah Elic \
blah blah blah Eric blah blah Eric blah blah \
blah blah blah blah blah Eric";

var myName = "Eric";
var hits = [];
var l = 0;
var count = 0;
var foundName = '';

for (var i = 0; i < text.length; i++) {
foundName = '';

if (text[i] === "E") {
for (var j = 0; j < myName.length; j++) {
foundName += text[i + j];
}

if (foundName === myName) {
for (var k = 0; k < myName.length; k++) {
hits.push(foundName[k]);
}
}
}
}

console.log(hits);

关于javascript - 从段落中搜索文本 - Javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27310365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com