gpt4 book ai didi

Javascript 微调 + 查找名称的精确匹配

转载 作者:行者123 更新时间:2023-12-04 11:25:46 27 4
gpt4 key购买 nike

是否有内置的 JavaScript 字符串方法可以帮助我微调这段代码以确保它只找到与名称完全匹配的内容?

这是我的代码。

/*jshint multistr:true */

var text = "Sid quick brown fox jumps over the lazy dog ";
var myName = "Sid";
var hits = [];

for (var i=0; i< text.length; i++){
if(text[i] === 'S'){
for(var j=i; j < i + myName.length; j++){
hits.push(text[j]);
}
}else{
console.log("Your name wasn't found!")
}

}
console.log(hits);

最佳答案

所以这是另一个解决方案,使用函数 match() ,但更简单:

/*jshint multistr:true */
var text = "Hey, how are you doing Sanda? My name is Emily.\
Nice to meet you Sada. Where does your name come from, Sana?\
is Sanda a slavic name?";
/*var myName = "Sanda";
hits = [];

for(var i=0; i < text.length; i++ ){
if (text[i] === myName[0])
for (var j=i; j< i + myName.length && j < text.length; j++ )
hits.push(text[j]);
}

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

var hits = text.match(/Sanda/g);

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

语法是 var <someVar> = <textToBeSearched>.match(/pattern/modifiers) .我的修改器g用于全局(搜索整个模式)。

更多信息在这里: http://www.w3schools.com/jsref/jsref_match.asp http://www.w3schools.com/js/js_regexp.asp

干杯!

关于Javascript 微调 + 查找名称的精确匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18434980/

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