473,666 Members | 2,073 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

matching first 3 characters

In summary, I don't know how/why the following code works and would like to
know.

I'm trying to match the first 3 characters of a variable (filename). The
code below crudely works, but only if I move "Activities " below "Fine Arts",
implying the code is not matching exactly the first 3 characters. I've left
the code in my testing state for the following questions:
1. How do I specifiy the match to include all 3 characters (not just a
single character match)?
2. What's the difference between 'indexOf' and 'search'? (I left both in the
code below)
3. What function does the operator and following number perform in the 'if'
statements? (I left both operators in the code below)
4. Am I on the right track using if/else if? Is this economical?

Any comments are warmly and eagerly welcome.
Thanks in advance for your help,
Matt

function searchResult(fi lename, myitemtext) {
var valu = filename;
Str=valu;
Str=Str.substri ng(3,Str.length *-1);
for (var i = 0; i<Str.length; i++)
{
if(valu.indexOf ("hh") !=-1)
alert("Heritage Hall");
else if(valu.search( "fa1" ) > -1)
alert("Fine Arts - First Floor");
else if(valu.search( "fa2" ) > -1)
alert("Fine Arts - Second Floor");
else if(valu.search( "fa3" ) > -1)
alert("Fine Arts - Third Floor");
else if(valu.search( "a1" ) > -1)
alert("Activiti es - First Floor");
else if(valu.search( "a2" ) > -1)
alert("Activiti es - Second Floor");
else if(valu.search( "a3" ) > -1)
alert("Activiti es - Third Floor");
else if(valu.indexOf ("b")!=-1)
alert("Business ");
else if(valu.indexOf ("dc")!=-1)
alert("Daycare" );
}
Aug 19 '05 #1
7 1917
Matt L. wrote:
I'm trying to match the first 3 characters of a variable (filename).
1. How do I specifiy the match to include all 3 characters (not just a
single character match)?
function startsWith(str, match) {
return (str.substr(0,m atch.length) == match);
}

Or alter this slightly if it really needs to be 3 characters.

2. What's the difference between 'indexOf' and 'search'? (I left both in the
code below)
indexOf is used to find a substring occurance in a string.
search is used to do a regular expression match in a string.
See http://www.regular-expressions.info/tutorial.html for information
about regular expressions.
3. What function does the operator and following number perform in the 'if'
statements? (I left both operators in the code below)
In this case they do the same things, because the regular expressions
you use are simple literal strings.
4. Am I on the right track using if/else if? Is this economical?
Well, I see some very weird things.
Particulary the fact that you create a substring that takes the end of
the string and then do a for loop for no apparent reason.
The
code below crudely works, but only if I move "Activities " below "Fine
Arts"


That is because the search for "a1" is not just for the start of the
string, but anywhere!

So for example:
filename = "abc";

if (filename.index Of("b") != 1)
alert("Found it!");
else if (filename.index Of("ab") != 1)
alert("This will never happen");

So there can never be an "ab" match if there was no "b" match.

What you need is probably something like this:

function searchResult(fi lename) {
var first3Chars = filename.substr (0, 3);
switch (first3Chars) {
case "hh" : // do something
break;
case "fa1" : // do something
break;
}
}
Aug 19 '05 #2
alu

"Matt L." <so*****@micros oft.com> wrote
In summary, I don't know how/why the following code works and would like to know.

I'm trying to match the first 3 characters of a variable (filename). The
code below crudely works, but only if I move "Activities " below "Fine Arts", implying the code is not matching exactly the first 3 characters. I've left the code in my testing state for the following questions:
1. How do I specifiy the match to include all 3 characters (not just a
single character match)?
2. What's the difference between 'indexOf' and 'search'? (I left both in the code below)
3. What function does the operator and following number perform in the 'if' statements? (I left both operators in the code below)
4. Am I on the right track using if/else if? Is this economical?

Any comments are warmly and eagerly welcome.
Thanks in advance for your help,
Matt

function searchResult(fi lename, myitemtext) {
var valu = filename;
Str=valu;
Str=Str.substri ng(3,Str.length *-1);
for (var i = 0; i<Str.length; i++)
{
if(valu.indexOf ("hh") !=-1)
alert("Heritage Hall");
else if(valu.search( "fa1" ) > -1)
alert("Fine Arts - First Floor");
else if(valu.search( "fa2" ) > -1)
alert("Fine Arts - Second Floor");
else if(valu.search( "fa3" ) > -1)
alert("Fine Arts - Third Floor");
else if(valu.search( "a1" ) > -1)
alert("Activiti es - First Floor");
else if(valu.search( "a2" ) > -1)
alert("Activiti es - Second Floor");
else if(valu.search( "a3" ) > -1)
alert("Activiti es - Third Floor");
else if(valu.indexOf ("b")!=-1)
alert("Business ");
else if(valu.indexOf ("dc")!=-1)
alert("Daycare" );
}

Hmm, the above loops for no apparent reason and the function is not closed;
I'm surprised it 'works crudely'.

You could try using a simple switch, which would take care of the match from
the start of the string - but note you will have to send a filename that
exactly matches the cases, or set the cases to exactly match the filename
because some of your filenames are in fact less than 3 characters long.
e.g., searchResult("h hw") would result in 'not found'
function searchResult(fi lename) {
var firstThree = filename.substr ing(0,3);

switch (firstThree) {
case "hh" :
alert("Heritage Hall");
break;
case "fa1" :
alert("Fine Arts - First Floor");
break;
case "fa2" :
alert("Fine Arts - Second Floor");
break;
default :
alert("not found")
}
}

-alu
Aug 19 '05 #3
Thanks Robert, the function you provided is exactly what I was looking for.

Amazing you could wade through my convoluted code and figure out what I was
trying to do. I will be enforcing a minimum unique 3 character filename
following the function you submitted.

The Regular Expression link you provided will also come in very handy.

I'm well on my way now.

Thanks again for your prompt help.
"Robert" <ro****@noreply .x> wrote in message
news:43******** *************** @news.xs4all.nl ...
Matt L. wrote:
I'm trying to match the first 3 characters of a variable (filename).
1. How do I specifiy the match to include all 3 characters (not just a
single character match)?


function startsWith(str, match) {
return (str.substr(0,m atch.length) == match);
}

Or alter this slightly if it really needs to be 3 characters.

2. What's the difference between 'indexOf' and 'search'? (I left both in the code below)


indexOf is used to find a substring occurance in a string.
search is used to do a regular expression match in a string.
See http://www.regular-expressions.info/tutorial.html for information
about regular expressions.
3. What function does the operator and following number perform in the 'if' statements? (I left both operators in the code below)


In this case they do the same things, because the regular expressions
you use are simple literal strings.
4. Am I on the right track using if/else if? Is this economical?


Well, I see some very weird things.
Particulary the fact that you create a substring that takes the end of
the string and then do a for loop for no apparent reason.
> The
> code below crudely works, but only if I move "Activities " below "Fine
> Arts"


That is because the search for "a1" is not just for the start of the
string, but anywhere!

So for example:
filename = "abc";

if (filename.index Of("b") != 1)
alert("Found it!");
else if (filename.index Of("ab") != 1)
alert("This will never happen");

So there can never be an "ab" match if there was no "b" match.

What you need is probably something like this:

function searchResult(fi lename) {
var first3Chars = filename.substr (0, 3);
switch (first3Chars) {
case "hh" : // do something
break;
case "fa1" : // do something
break;
}
}

Aug 19 '05 #4
Thank you Alu for your prompt help! That is exactly what I was after!
"alu" <no**@none.co m> wrote in message
news:RI******** ***********@new s20.bellglobal. com...

"Matt L." <so*****@micros oft.com> wrote
In summary, I don't know how/why the following code works and would like to
know.

I'm trying to match the first 3 characters of a variable (filename). The
code below crudely works, but only if I move "Activities " below "Fine

Arts",
implying the code is not matching exactly the first 3 characters. I've

left
the code in my testing state for the following questions:
1. How do I specifiy the match to include all 3 characters (not just a
single character match)?
2. What's the difference between 'indexOf' and 'search'? (I left both in

the
code below)
3. What function does the operator and following number perform in the

'if'
statements? (I left both operators in the code below)
4. Am I on the right track using if/else if? Is this economical?

Any comments are warmly and eagerly welcome.
Thanks in advance for your help,
Matt

function searchResult(fi lename, myitemtext) {
var valu = filename;
Str=valu;
Str=Str.substri ng(3,Str.length *-1);
for (var i = 0; i<Str.length; i++)
{
if(valu.indexOf ("hh") !=-1)
alert("Heritage Hall");
else if(valu.search( "fa1" ) > -1)
alert("Fine Arts - First Floor");
else if(valu.search( "fa2" ) > -1)
alert("Fine Arts - Second Floor");
else if(valu.search( "fa3" ) > -1)
alert("Fine Arts - Third Floor");
else if(valu.search( "a1" ) > -1)
alert("Activiti es - First Floor");
else if(valu.search( "a2" ) > -1)
alert("Activiti es - Second Floor");
else if(valu.search( "a3" ) > -1)
alert("Activiti es - Third Floor");
else if(valu.indexOf ("b")!=-1)
alert("Business ");
else if(valu.indexOf ("dc")!=-1)
alert("Daycare" );
}

Hmm, the above loops for no apparent reason and the function is not

closed; I'm surprised it 'works crudely'.

You could try using a simple switch, which would take care of the match from the start of the string - but note you will have to send a filename that
exactly matches the cases, or set the cases to exactly match the filename
because some of your filenames are in fact less than 3 characters long.
e.g., searchResult("h hw") would result in 'not found'
function searchResult(fi lename) {
var firstThree = filename.substr ing(0,3);

switch (firstThree) {
case "hh" :
alert("Heritage Hall");
break;
case "fa1" :
alert("Fine Arts - First Floor");
break;
case "fa2" :
alert("Fine Arts - Second Floor");
break;
default :
alert("not found")
}
}

-alu

Aug 19 '05 #5
ASM
Matt L. wrote:
In summary, I don't know how/why the following code works and would like to
know.

I'm trying to match the first 3 characters of a variable (filename). The
code below crudely works, but only if I move "Activities " below "Fine Arts",
implying the code is not matching exactly the first 3 characters. I've left
the code in my testing state for the following questions:
1. How do I specifiy the match to include all 3 characters (not just a
single character match)?
2. What's the difference between 'indexOf' and 'search'? (I left both in the
code below)
url = self.location; // get url of displayed page

url = url.search; // extract what follow url (?name=Smith&su rname=Wil )

i = url.indexOf('?' ) // gives index of '?' in string url
i.e :
truc = 'ste+phane moriaux'
i = truc.indexOf('+ '); // gives 3 ( i = 3 ) (count begin with 0)
j = truc.search('+' ); // gives an error
j = truc.search('e' ); // gives 2 find what's different

To get what follow url and use it in JS :

url = self.location; // page's url
url = url.search; // gives something as : ?store=al
url = url.substring(1 ) // gives something as : store=al
url = url.substring(6 ); // gives : al

Same faster :

url = self.location.s earch.substring (7);

var mesg = ''
switch (url) {
case 'hh' :
mesg = 'Heritage Hall';
break;
case 'fa1' :
mesg = 'Fine Arts - First Floor';
break;
case 'fa2' :
mesg = 'Fine Arts - Second Floor';
break;
default :
mesg = 'not found'
}
}
alert(mesg);
3. What function does the operator and following number perform in the 'if'
statements? (I left both operators in the code below)
== : equal (same)
!= : non equal (different) : superior (strictly)
= : superior or equal 4. Am I on the right track using if/else if? Is this economical?


cf above about switch

--
Stephane Moriaux et son [moins] vieux Mac
Aug 19 '05 #6
JRS: In article <HvKdnZ2dnZ3aVd 7fnZ2dnSRxmN6dn Z2dRVn-
0p*****@comcast .com>, dated Fri, 19 Aug 2005 09:29:13, seen in
news:comp.lang. javascript, Matt L. <so*****@micros oft.com> posted :
In summary, I don't know how/why the following code works and would like to
know.

I'm trying to match the first 3 characters of a variable (filename). The
code below crudely works, but only if I move "Activities " below "Fine Arts",
implying the code is not matching exactly the first 3 characters.
You are supplying a number of characters which is not always three, and
testing for them to appear anywhere. Change the test from > -1 to == 0
to consider only a match at the beginning.
I've left
the code in my testing state for the following questions:
1. How do I specifiy the match to include all 3 characters (not just a
single character match)?
Difficult when the value of 3 seems to vary.
2. What's the difference between 'indexOf' and 'search'? (I left both in the
code below)
indexOf returns a position, and searches for a substring; search is for
a RegExp argument, but evidently can be used with a plain string.
3. What function does the operator and following number perform in the 'if'
statements? (I left both operators in the code below)
If indexOf does not find, it returns -1.
4. Am I on the right track using if/else if? Is this economical?


No.

Always look out for a means of using a list of entries; it's efficiently
maintainable. Consider :

var Tbl = [ {x:"hh", s:"Heritage Hall"},
{x:"a1", s:"Activities - First Floor"},
{x:"dc", s:"DayCare"} ]

function sR(filename) {
for (var j=0; j<Tbl.length; j++) with (Tbl[j])
if (!filename.inde xOf(x)) return s
return "Eh?" }

alert(sR(NameOf File))
You will still need to but more specific items, such as "a1", before
more general ones, such as "a".

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Aug 19 '05 #7
ASM
Dr John Stockton wrote:
Consider :

var Tbl = [ {x:"hh", s:"Heritage Hall"},
{x:"a1", s:"Activities - First Floor"},
{x:"dc", s:"DayCare"} ]

function sR(filename) {
for (var j=0; j<Tbl.length; j++) with (Tbl[j])
if (!filename.inde xOf(x)) return s
that did only work with :

if (filename.index Of(x)) return s
return "Eh?" }

alert(sR(NameOf File))

my test : alert(sR('Name_ a1_OfFile'))
--
Stephane Moriaux et son [moins] vieux Mac
Aug 20 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
5483
by: | last post by:
Hi, I'm fairly new to regular expressions, and this may be a rather dumb question, but so far I haven't found the answer in any tutorial or reference yet... If I have f.i. the string "The {{{{power of {{{{regular expressions}}}} comes from}}}} the ability to include alternatives and repetitions in the pattern." from which I want to extract chunks starting with "{{{{" and ending with "}}}}".
8
1913
by: Synonymous | last post by:
Hello, Can regular expressions compare file names to one another. It seems RE can only compare with input i give it, while I want it to compare amongst itself and give me matches if the first x characters are similiar. For example: cccat
1
3310
by: Antony Paul | last post by:
Hi all, What are the characters used for pattern matching with PostgreSQL 7.3. I know it is using % and _ . Any other characters ?. rgds Atnony Paul ---------------------------(end of broadcast)--------------------------- TIP 5: Have you checked our extensive FAQ?
8
2461
by: John Hazen | last post by:
I want to match one or two instances of a pattern in a string. According to the docs for the 're' module ( http://python.org/doc/current/lib/re-syntax.html ) the '?' qualifier is greedy by default, and adding a '?' after a qualifier makes it non-greedy. > The "*", "+", and "?" qualifiers are all greedy... > Adding "?" after the qualifier makes it perform the match in > non-greedy or minimal fashion...
15
16738
by: Mark Rae | last post by:
Hi, I'm trying to construct a RegEx pattern which will validate a string so that it can contain: only the numerical characters from 0 to 9 i.e. no decimal points, negative signs, exponentials etc only the 26 letters of the standard Western alphabet in either upper or lower case spaces i.e. ASCII character 32
3
2160
newnewbie
by: newnewbie | last post by:
I need help with a query where I am trying to match and display the value (First 18 characters of it) in one table that matches the first 18 characters of the field value in another table. Tables are not linked. Tables, fields and data examples: Table # 1 Name: Claims Filed Name: Name Field Value example: 2006120800011CLT108.TIF#http://fl-jax-sharp/sites%2Fclaims%2FClaims%2F2006%...and it goes on Table # 2 Name: Raw Data Field Name:...
7
4395
by: blaine | last post by:
Hey everyone, For the regular expression gurus... I'm trying to write a string matching algorithm for genomic sequences. I'm pulling out Genes from a large genomic pattern, with certain start and stop codons on either side. This is simple enough... for example: start = AUG stop=AGG BBBBBBAUGWWWWWWAGGBBBBBB
11
4833
by: tech | last post by:
Hi, I need a function to specify a match pattern including using wildcard characters as below to find chars in a std::string. The match pattern can contain the wildcard characters "*" and "?", where "*" matches zero or more consecutive occurrences of any character and "?" matches a single occurrence of any character. Does boost or some other library have this capability? If boost does have this, do i need to include an entire
2
1642
by: lorlarz | last post by:
Looking for feedback on Matching Exercises Maker/ Builder: http://mynichecomputing.com/ReadIt/translateT.html For one thing, I am concerned about storing the matching kwork (known word) as the className of the li which is the answer. I think this may be problematic. I also worry about using the ul as the container for the whole thing.
0
8356
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8871
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8783
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8552
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8640
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6198
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4369
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2773
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1776
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.