dcsimg
www.webdeveloper.com
Results 1 to 6 of 6

Thread: Please Explain code

  1. #1
    Join Date
    Jun 2014
    Posts
    3

    Please Explain code

    I am new in JavaScript and I cannot understand some code given below .Can anyone explain Line 3 and Line 4 ?

    var text = prompt("What is this ?");
    var firstChar = text.indexOf("World War II");
    if (firstChar !== -1) {
    text = text.slice(0, firstChar) + "the Second World War" + text.slice(firstChar + 12);
    }
    alert (text);

  2. #2
    Join Date
    Nov 2010
    Posts
    1,119
    it's not worth explaining because it makes no sense. What are you trying to do?

  3. #3
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,877
    Sorry, my brain just imploded, can't make sense of it either.
    STOP using $ prefix on JavaScript variable names...
    Please remember to wrap any code you have in forum tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  4. #4
    Join Date
    Jun 2014
    Posts
    3
    If you cannot help then stay out of my post .Better stay away from forum .

    Quote Originally Posted by xelawho View Post
    it's not worth explaining because it makes no sense. What are you trying to do?

  5. #5
    Join Date
    Jun 2014
    Posts
    3

    no place for beginners.

    I thought, I would find help here..Here Everyone is too advanced , no place for beginners.
    Quote Originally Posted by \\.\ View Post
    Sorry, my brain just imploded, can't make sense of it either.

  6. #6
    first line asks a question putting whatever is typed in into the 'text' variable.

    the next line finds the first instance of "World War II" in that 'text' and puts that into the 'firstChar' variable. The 'indexOf' function will return -1 if there is no match.

    The 'IF' statement checks if it's not -1, in which case there was a match.

    ... so it then uses 'slice' to take all text before the match, plug in "the Second World War", then all text after the match.

    Next we close the if statement with }

    Then we alert the result.

    Which is a VERY complex way of simply going:

    Code:
    var text = prompt("What is this ?").replace(
    	'World War II', 'the Second World War'
    );
    alert (text);
    Though a more complex regex would probably be in order.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles