/    Sign up×
Community /Pin to ProfileBookmark

Help with javascript function

How do I add input validation to this function so that the test cases work.
Test cases 1-3 should output a truncated string (or the original, if the “targetLength” value isn’t greater than the string length) , while test cases 4 and 5 will output the string “Invalid Input”.

Below is the function:

function truncate(inputString, targetLength){
return inputString.substr(0, targetLength);

}

//test cases
var x = “It happened just a week ago”;
var y;
console.log(“1: ” + truncate(x, 10));
console.log(“2: ” + truncate(x)); // should output the unmodified string
console.log(“3: ” + truncate(10, 10));
console.log(“4: ” + truncate(y, 10));
console.log(“5: ” + truncate(x, “Bob”));

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@rtretheweyFeb 27.2015 — Try something like:
<i>
</i>function truncate(inputString, targetLength){
var len = inputString.length;
var result = '';
if (targetLength &gt; 0) { len = targetLength; }
if (inputString.length &gt; 0) { result = inputString.substr(0, len); }
return result;
}

This code checks to make sure that the parameters are valid - or at least not empty/null.
Copy linkTweet thisAlerts:
@MaryLynauthorFeb 27.2015 — I tried this and it worked. Thank you!

Try something like:
<i>
</i>function truncate(inputString, targetLength){
var len = inputString.length;
var result = '';
if (targetLength &gt; 0) { len = targetLength; }
if (inputString.length &gt; 0) { result = inputString.substr(0, len); }
return result;
}

This code checks to make sure that the parameters are valid - or at least not empty/null.[/QUOTE]
×

Success!

Help @MaryLyn 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 5.20,
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: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

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

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...