/    Sign up×
Community /Pin to ProfileBookmark

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);

to post a comment
JavaScript

5 Comments(s)

Copy linkTweet thisAlerts:
@xelawhoJun 08.2014 — it's not worth explaining because it makes no sense. What are you trying to do?
Copy linkTweet thisAlerts:
@rootJun 08.2014 — Sorry, my brain just imploded, can't make sense of it either.
Copy linkTweet thisAlerts:
@najmulauthorJun 09.2014 — If you cannot help then stay out of my post .Better stay away from forum .

it's not worth explaining because it makes no sense. What are you trying to do?[/QUOTE]
Copy linkTweet thisAlerts:
@najmulauthorJun 09.2014 — I thought, I would find help here..Here Everyone is too advanced , no place for beginners.
Sorry, my brain just imploded, can't make sense of it either.[/QUOTE]
Copy linkTweet thisAlerts:
@deathshadowJun 09.2014 — 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:

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.
×

Success!

Help @najmul spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...