- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Constructing a sentence based on array of words and punctuations using JavaScript
Problem
We are required to write a JavaScript function that takes in an array of words and punctuations. Our function should join array elements to construct a sentence based on the following rules −
there must always be a space between words;
there must not be a space between a comma and word on the left;
there must always be one and only one period at the end of a sentence.
Example
Following is the code −
const arr = ['hey', ',', 'and', ',', 'you']; const buildSentence = (arr = []) => { let res = ''; for(let i = 0; i < arr.length; i++){ const el = arr[i]; const next = arr[i + 1]; if(next === ','){ res += el; }else{ if(!next){ res += `${el}.`; }else{ res += `${el} `; } } } return res; }; console.log(buildSentence(arr));
Output
hey, and, you.
- Related Articles
- Replace all occurrence of specific words in a sentence based on an array of words in JavaScript
- Constructing a string based on character matrix and number array in JavaScript
- Order an array of words based on another array of words JavaScript
- Constructing 2-D array based on some constraints in JavaScript
- Constructing an array of smaller elements than the corresponding elements based on input array in JavaScript
- Reverse all the words of sentence JavaScript
- Counting number of words in a sentence in JavaScript
- Removing punctuations from a string using JavaScript
- Sorting string of words based on the number present in each word using JavaScript
- Constructing multiples array - JavaScript
- How to find capitalized words and add a character before that in a given sentence using JavaScript?
- Search and update array based on key JavaScript
- Sorting Array based on another array JavaScript
- Constructing product array in JavaScript
- Arranging words by their length in a sentence in JavaScript

Advertisements