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?
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);
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?
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);
Share
Improve this question
edited Aug 3, 2020 at 12:31
David Buck
3,83036 gold badges43 silver badges62 bronze badges
asked Aug 26, 2013 at 0:13
sidphsidph
211 gold badge1 silver badge2 bronze badges
1
- 1 why not with a regexp as @Björn Roberg suggests? That's just made for this… – philipp Commented Sep 5, 2013 at 15:10
10 Answers
Reset to default 5So here's another solution, using function match()
, but simpler:
/*jshint multistr:true */
var text = "Hey, how are you doing Sanda? My name is Emily.\
Nice to meet you Sada. Where does your name e 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).
More info here: http://www.w3schools./jsref/jsref_match.asp http://www.w3schools./js/js_regexp.asp
Cheers!
The OP's example is from codecademy, so if anyone is searching for answers specifically related to Javascript: Lesson 6/7 this is what I came up with:
/*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 plete newbies so the answer they were looking for was to be done using for
loops and extensive if
/else
statements to give us practice.
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:
/*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!
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);
}
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
Also encountered this exercise in Code Academy's Javascript fundamentals course.
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 $2 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);
}
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."
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);
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:
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.");
}
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.
/*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]);
}
}
Here is the solution with 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);
};