Adding paragraph tag to substrings within a string in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in a string str as the first argument and an array of strings, arr as the second argument. We need to add a closed pair of paragraph tag <p> and </p> to wrap the substrings in str that exist in arr. If two such substrings overlap, we need to wrap them together by only one pair of closed paragraph tag.

Also, if two substrings wrapped by paragraph tags are consecutive, we need to combine them.

For example −

If the input string and the array are −

const str = 'kkkllmm';
const arr = ["kkk","kkl","lm"];

Then the output should be −

const output = '<p>kkkllm</p>m';

Example

The code for this will be −

 Live Demo

const str = 'kkkllmm';
const arr = ["kkk","kkl","lm"];
var addParagraphTag = (str = [], arr = []) => {
   if(!arr.length){
      return str
   };
   const { length } = str;
   let paraBoolean = new Array(length).fill(false);
   let end = 0;
   for (let i = 0; i < length; i++){
      for (let j = 0; j < arr.length; j++){
         let word = arr[j];
         if (str.startsWith(word,i)) {
            end = Math.max(end, i + word.length);
         };
      }
      paraBoolean[i] = end > i;
   };
   let curr = 0;
   let newStr = '';
   while (curr < length) {
      while(paraBoolean[curr] === false) {
         newStr += str[curr++];
      }
      if (curr >= length) break;
      newStr += '<p>';
      let startBold = curr;
      while (paraBoolean[curr] === true) curr++;
      newStr += str.slice(startBold, curr);
      newStr += '</p>';
   };
   return newStr;
};
console.log(addParagraphTag(str, arr));

Output

And the output in the console will be −

<p>kkkllm</p>m

raja
Published on 26-Feb-2021 08:05:13
Advertisements