Last active
May 3, 2018 01:30
-
-
Save juliaamosova/eff154f9e3c75a2e85d5b9c42c0c6e9e to your computer and use it in GitHub Desktop.
Checkio: Find the first word in a given string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
You are given a string where you have to find its first word. | |
When solving a task pay attention to the following points: | |
There can be dots and commas in a string. | |
A string can start with a letter or, for example, a dot or space. | |
A word can contain an apostrophe and it's a part of a word. | |
The whole text can be represented with one word and that's it. | |
Input: A string. | |
Output: A string. | |
Precondition: the text can contain a-z A-Z , . ' | |
*/ | |
function firstWord(a, b) { | |
// returns the first word in a given text. | |
var originString = ''; | |
var firstWord = ''; | |
var wordStarted = false; | |
if (typeof b != "undefined") { | |
originString = a + b; | |
} else { | |
originString = a; | |
} | |
for (var i = 0; i < originString.length ; i++) { | |
if (wordStarted === false) { | |
if (originString[i] === " " || originString[i] === "," || originString[i] === ".") { | |
continue; | |
} else { | |
wordStarted = true; | |
firstWord += originString[i]; | |
} | |
} else { | |
if (originString[i] === " " || originString[i] === "," || originString[i] === ".") { | |
break; | |
} else { | |
firstWord += originString[i]; | |
} | |
} | |
} | |
return firstWord; | |
} | |
var assert = require('assert'); | |
if (!global.is_checking) { | |
console.log('Example:') | |
console.log(firstWord("Hello world")) | |
// These "asserts" using for self-checking and not for auto-testing | |
assert.equal(firstWord("Hello world"), "Hello") | |
assert.equal(firstWord(" a word "), "a") | |
assert.equal(firstWord("don't touch it"), "don't") | |
assert.equal(firstWord("greetings, friends"), "greetings") | |
assert.equal(firstWord("... and so on ..."), "and") | |
assert.equal(firstWord("hi"), "hi") | |
console.log("Coding complete? Click 'Check' to earn cool rewards!"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment