strings.js
[edit | edit source]// This program splits a given comma-separated name into first and last name // components and then displays the name. // // References: // https://www.mathsisfun.com/temperature-conversion.html // https://en.wikibooks.org/wiki/JavaScript main(); functionmain() { varname; varlast; varfirst; name=getName(); last=getLast(name); first=getFirst(name); displayName(first,last); } functiongetName() { varname; varindex; do { name=input("Enter name (last, first):"); index=name.indexOf(","); }while(index<0); returnname; } functiongetLast(name) { varlast; varindex; index=name.indexOf(","); if(index<0) { last=""; } else { last=name.substring(0,index); } returnlast; } functiongetFirst(name) { varfirst; varindex; index=name.indexOf(","); if(index<0) { first=""; } else { first=name.substring(index+1); first=first.trim(); } returnfirst; } functiondisplayName(first,last) { output("Hello "+first+" "+last+"!"); } functioninput(text){ if(typeofwindow==='object'){ returnprompt(text) } elseif(typeofconsole==='object'){ constrls=require('readline-sync'); varvalue=rls.question(text); returnvalue; } else{ output(text); varisr=newjava.io.InputStreamReader(java.lang.System.in); varbr=newjava.io.BufferedReader(isr); varline=br.readLine(); returnline.trim(); } } functionoutput(text){ if(typeofdocument==='object'){ document.write(text); } elseif(typeofconsole==='object'){ console.log(text); } else{ print(text); } }
Try It
[edit | edit source]Copy and paste the code above into one of the following free online development environments or use your own JavaScript compiler / interpreter / IDE.
- Chapman.edu: Online JavaScript Interpreter
- CodeChef
- GDB Online
- Ideone
- JS.do
- paiza.IO
- PythonTutor
- repl.it
