0

I have a question on how to store a string in Javascript when you only know the first couple letters. Here is an example. The HTML code is this:

<HTML>

<HEAD>
    <TITLE>Your Title Here</TITLE>
</HEAD>

<BODY BGCOLOR="FFFFFF">
    <CENTER>
        <IMG SRC="clouds.jpg" ALIGN="BOTTOM"> </CENTER>
    <HR>
    <a href="http://somegreatsite.com">Link Name</a> is a link to another nifty site
    <H1>This is a Header</H1>
    <H2>This is a Medium Header</H2> Send me mail at <a href="mailto:support@yourcompany.com">
support@yourcompany.com</a>.
    <P> This is a new paragraph!
        <A href="/003U0000015Rmza">Persons's Name/A> </P>
<P> <B>This is a new paragraph!</B> </P>
<BR> <B><I>This is a new sentence without a paragraph break, in bold italics.</I></B>
<HR>
</BODY>
</HTML>

I need to store the full string of '003U0000015Rmza', but I will only know that it starts with '003'.

Is there a way in Javascript to search for the characters '003', and once it's found, store the full string in a variable?

Thanks in advance!

Mohamad Shiralizadeh
  • 8,329
  • 6
  • 58
  • 93
Alex Klinghoffer
  • 349
  • 4
  • 7
  • 15

2 Answers2

0

You want to have a way to see if a string starts with a certain pattern. One easy way is to overload the String type to have a startsWith() function .

Look at this example.

Community
  • 1
  • 1
Gui Rava
  • 448
  • 4
  • 6
0

This is where String.indexOf() can come in handy.

inThis.indexOf(findThat) function searches the string it's called on for the string you pass in. It returns a number stating where to find the string you looked for (findThat) within the string that you looked in (inThis). If it doesn't find the string at all, it returns -1, which isn't a valid position in any string.

To use this to find whether inThat starts with findThis, you can do something like this:

if (inThis.indexOf(findThat) === 0) {
    // do something
}

To store that string somewhere, you might try this:

var myString; // The place where we'll store the string
if (theLink.href.indexOf('003') === 0) {
    // This is the string we need to store
    myString = theLink.href;
}

This works because the first character in any string is at position 0. So if indexOf found '003' at position 0, then we know the string starts with '003'.

The Spooniest
  • 2,863
  • 14
  • 14