Javascript 微调 + 查找名称的精确匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18434980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript finetunning + find exact match for a name
提问by sidph
Is there a built in JavaScript string method that can help me fine tune this code to make sure it only finds exact matches for the name?
是否有内置的 JavaScript 字符串方法可以帮助我微调此代码以确保它只找到名称的完全匹配项?
Here's my code.
这是我的代码。
/*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);
回答by Sanda
So here's another solution, using function match()
, but simpler:
所以这是另一个解决方案,使用 function 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);
Syntax is var <someVar> = <textToBeSearched>.match(/pattern/modifiers)
. My modifier g
is for global (searches the entire pattern).
语法是var <someVar> = <textToBeSearched>.match(/pattern/modifiers)
. 我的修饰符g
用于全局(搜索整个模式)。
More info here: http://www.w3schools.com/jsref/jsref_match.asphttp://www.w3schools.com/js/js_regexp.asp
更多信息在这里:http: //www.w3schools.com/jsref/jsref_match.asp http://www.w3schools.com/js/js_regexp.asp
Cheers!
干杯!
回答by phoenixlaef
The OP's example is from codecademy, so if anyone is searching for answers specifically related to Javascript: Lesson 6/7this is what I came up with:
OP 的示例来自 codecademy,所以如果有人正在寻找与Javascript相关的答案:第 6/7 课,这就是我想出的:
/*jshint multistr:true */
var text = "How are you \
doing Sabe? What are you \
up to Sabe? Can I watch \
Sabe?";
var myName = "Sabe";
var hits = [];
for (var i = 0; i < text.length; i++) {
if (text[i] === 'D') {
for (var j = i; j < (i + myName.length); j++) {
hits.push(text[j]);
}
}
}
if (hits.length === 0) {
console.log("Your name wasn't found!");
} else {
console.log(hits);
}
I then decided, like the OP, to do the extra challenge which was creating a string that required an exact match. The codecademy javascript course is for complete newbies so the answer they were looking for was to be done using for
loops and extensive if
/else
statements to give us practice.
然后我决定,像 OP 一样,进行额外的挑战,即创建一个需要完全匹配的字符串。codecademy javascript 课程是为完全的新手准备的,所以他们正在寻找的答案是使用for
循环和广泛的if
/else
语句来给我们练习。
The extended version from a learning curve point of view:
从学习曲线的角度来看,扩展版:
/*jshint multistr:true */
var text = "The video provides a powerful way to help you prove \
your point. When you click Online video, you can paste in the \
embed code for the video you want to add. You can also type a \
keyword to search online for the video that best fits your document.";
var theWord = "video";
var hits = [];
for (var i = 0; i < text.length; i++) {
if (theWord === text.substr(i,theWord.length)) {
hits.push(i);
i += theWord.length-1;
}
}
if (hits.length) {
for (i = 0; i < hits.length; i++) {
console.log(hits[i],text.substr(hits[i],theWord.length));
}
} else {
console.log("No matches found.");
}
Then there is match()
mentioned by @Sanda which is good to know for real life instances:
然后match()
@Sanda 提到这对现实生活中的例子很有帮助:
/*jshint multistr:true */
var text = "The video provides a powerful way to help you prove \
your point. When you click Online video, you can paste in the \
embed code for the video you want to add. You can also type a \
keyword to search online for the video that best fits your document.";
var hits = text.match(/video/g);
if ( hits.length === 0) {
console.log("No matches found.");
} else {
console.log(hits);
}
I hope this helps the codecademy folk!
我希望这对代码学院的人有所帮助!
回答by Wake Up
var text = "Blah blah blah blah blah blah Hafeez \
blah blah blah Hafeez blah blah Hafeez blah blah \
blah blah blah blah blah Huzaif, Hazere";
var myName = "Hafeez";
var hits = [];
for (var i =0; i < text.length ; i++)
{
if(text[i] === 'H')
{
for(var j = i; j < (myName.length + i); j++)
{
if (text.substring(i, (myName.length + i)) === myName)
{
hits.push(text[j])
}
}
}
}
if(hits === 0)
{
console.log("Your name was'nt found");
}
else
{
console.log(hits);
console.log(hits.length);
}
回答by Jonathan
Use this to only match exact names, and not partial names.
使用它仅匹配精确名称,而不匹配部分名称。
var text = "Hello my name is Johny, are you Sandra, Sandra?";
var names = ["Sandra", "John"];
for (var i = 0; i < names.length; i++) {
var re = new RegExp("\b" + names[i] + "\b", "g");
document.write("Matches for " + names[i] + ": " + (text.match(re) ? text.match(re).length : 0) + "<br>");
}
\b
Means word boundary in Regex
\b
正则表达式中的意思是词边界
回答by Calipso
Also encountered this exercise in Code Academy's Javascript fundamentals course.
在 Code Academy 的 Javascript 基础课程中也遇到过这个练习。
My solution is below. Quite basic but did the job.
我的解决方案如下。很基本,但完成了工作。
var text = "There is a real risk of the British economy being harmed Olly which has the potential to create an environment in which businesses could go under and Olly jobs could be lost. The economic Oggle uncertainty was tangible yesterday as global financial markets lost Olly up to Trillion USD value and the pound was at it's lowest value for 30 years before recovering somewhat."
var myName = "Olly"
var hits = []
for (var i = 0; i < text.length; i++) {
if (text[i] === "O" && text[i +1] === "l" && text [i +2] === "l" && text[i + 3] === "y") {
for(var j = i; j < (myName.length + i); j++) {
hits.push(text[j]);
}
}
}
if (hits.length === 0) {
console.log("Your name wasn't found!");
} else {
console.log(hits);
}
回答by Mkur
That's my own solution, using substring() function and search() function, that is a built-in JavaScript string method that checks in the text to find the word you are looking for. Upon success it will return you the position of the text that the word exists or -1 value if it fails. It is just another way to do it.
这是我自己的解决方案,使用 substring() 函数和 search() 函数,这是一个内置的 JavaScript 字符串方法,可以检查文本以查找您要查找的单词。成功后,它将返回该单词存在的文本位置,如果失败,它将返回 -1 值。这只是另一种方法。
/*jshint multistr:true */
var text = "hey wassup mike? \
wanna play football with mike, maria and antonis?!??!??!?!";
var myName = "mike";
var hits = [];
var pos = text.search(myName);
while(pos !== -1) {
for (var j = 0; j < myName.length; j++) {
hits.push(myName[j]);
}
text = text.substring(pos+myName.length,text.length);
pos = text.search(myName);
}
if(hits === "")
{
console.log("Your name wasn't found!");
}
else
{
for (var h = 0; h < hits.length; h++) {
console.log(hits[h]);
}
}
回答by samiralibabic
Here is the solution with substr:
这是带有 substr 的解决方案:
/*jshint multistr:true */
var text = "Lampe hinab la Samir licht schen er te recht. \
Furchtete verodeten wo te Song flanierte \
grundlich er Samir he. Bekam einem blank \
da so schlo mu so.",
myName = "Samir",
hits = [];
for (var i = 0; i < text.length; i++) {
if (text[i] === myName[0]) {
var substr = text.substr(i, myName.length);
if (substr === myName) {
for (var j = i; j < i + myName.length; j++) {
hits.push(text[j]);
}
}
}
}
if (hits.length === 0) {
console.log ("Your name wasn't found!");
} else {
console.log (hits);
};
回答by Math chiller
anyway heres some better code
无论如何,这里有一些更好的代码
check(0);
function check(start){
if ( text.subStr(start).indexOf(myName) >= 0 ){
hits++;
check(text.subStr(start).indexOf(myName));
}
}
if (hits < 1 ){
console.log("Your name wasn't found!")
}
console.log(hits);
still havent checked if it works but its the general idea
还没有检查它是否有效,但它的总体思路
so in answer yes "there's a built in Javascript string method that can help me (you) fine tune this code to make sure it only finds exact matches for the name."
所以回答是“有一个内置的 Javascript 字符串方法可以帮助我(你)微调这段代码,以确保它只找到与名称完全匹配的内容。”
回答by Bj?rn Roberg
You could try using regular expressions:
您可以尝试使用正则表达式:
var text = "Sid quick brown fox jumps over the lazy dog ";
var myName = "Sid";
var re = new RegExp(myName);
re.exec(text);
// => ["Sid"]
or if you necessarily want a string method:
或者如果你一定想要一个字符串方法:
myName.match(re);
回答by Christian
I don't know if this is all that different than some other answers, but this is how I did it without using RegEx and still filling the array variable with all occurrences of the string in question. As well, I only used the added String method of substring() to do it, which makes this another possible answer. Hope this helps:
我不知道这是否与其他一些答案完全不同,但这就是我在不使用 RegEx 的情况下做到的,并且仍然用所有出现的有问题的字符串填充数组变量。同样,我只使用了 substring() 添加的 String 方法来完成它,这使得这是另一个可能的答案。希望这可以帮助:
var text = "blah bhlekm kdnclwi Christian blah blah, lots of blah in this text, blahChristian got one more Christian, and that's it.";
var myName="Christian";
var hits = [];
for (i=0; i<text.length; i++){
if (text.substring(i, i+ myName.length) === myName){
hits.push(text.substring(i, i+myName.length));
}
}
if (hits.length == 0){
console.log("Your name wasn't found!");
}else{
console.log("your name showed up " + hits.length + " times.");
}