Categories
JavaScript Answers

How to Split a string based on multiple delimiters with JavaScript?

To split a string based on multiple delimiters with JavaScript, we can create a regex that matches all the delimiters and use that with the JavaScript string’s split method.

For instance, we can write:

const x = "adfds+fsdf-sdf";
const separators = [' ', '\\\+', '-', '\\\(', '\\\)', '\\*', '/', ':', '\\\?'];
const tokens = x.split(new RegExp(separators.join('|'), 'g'));
console.log(tokens);

We have the x string we want to split into a string array by the + and – signs.

Then we define the separators array with the delimiters we want to split the string by.

Next, we have new RegExp(separators.join('|'), 'g') to create the regex that matches all the delimiters listed in separators.

The | symbol lets us match any of the delimuters above.

The 'g' flag searches for all matches of the pattern in the string.

Finally, we call split with the regex to split the string.

Therefore, we get ["adfds","fsdf","sdf"] as a result.

Categories
JavaScript Answers

How to Paste Content as Plain Text Into the Summernote Editor?

To paste content as plain text into the Summernote editor, we add our own onPaste callback that calls the document.execCommand method.

For instance, we can write:

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" />
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.18/summernote.min.js" integrity="sha512-kZv5Zq4Cj/9aTpjyYFrt7CmyTUlvBday8NGjD9MxJyOY/f2UfRYluKsFzek26XWQaiAp7SZ0ekE7ooL9IYMM2A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.18/summernote-bs4.min.css" integrity="sha512-pDpLmYKym2pnF0DNYDKxRnOk1wkM9fISpSOjt8kWFKQeDmBTjSnBZhTd41tXwh8+bRMoSaFsRnznZUiH9i3pxA==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<div id="summernote">Hello Summernote</div>

to add the jQuery and Summernote libraries and the Bootstrap and Summernote CSS.

We also add the div that we will use for the Summernote editor.

Then we write:

$('#summernote').summernote({
  callbacks: {
    onPaste(e) {
      const bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('Text');
      e.preventDefault();
      document.execCommand('insertText', false, bufferText);
    }
  }
});

We call summernote with an object that has the callbacks.onPaste method.

In the method, we get the pasted text with:

const bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('Text');

Then we call e.preventDefault to stop the default behavior.

Finally, we write:

document.execCommand('insertText', false, bufferText);

to paste plain text.

Categories
JavaScript Answers

How to Determine if a String is a Base64 String Using JavaScript?

To determine if a string is a base64 string using JavaScript, we can check if a base64 string against a regex.

For instance, we can write:

const base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;

console.log(base64regex.test("abc"));
console.log(base64regex.test("U29tZVN0cmluZ09idmlvdXNseU5vdEJhc2U2NEVuY29kZWQ="));

We define the base64regex that matches any string that has 4 letters and numbers in the first group.

Then we check of groups of 2 letters and number or groups of 3 letters and numbers with equal signs after them for padding.

Therefore, the first console log will log false.

And the 2nd one will log true.

Categories
JavaScript Answers

How to Wrap Text in a Canvas Element with JavaScript?

To wrap text in a canvas element with JavaScript, we have to do the calculation for wrapping the text ourselves.

For instance, we write:

<canvas style='width: 300px; height: 300px'></canvas>

to create the canvas.

Then we write:

const wrapText = (ctx, text, x, y, maxWidth, lineHeight) => {
  const words = text.split(' ');
  let line = '';
  for (const [index, w] of words.entries()) {
    const testLine = line + w + ' ';
    const metrics = ctx.measureText(testLine);
    const testWidth = metrics.width;
    if (testWidth > maxWidth && index > 0) {
      ctx.fillText(line, x, y);
      line = w + ' ';
      y += lineHeight;
    } else {
      line = testLine;
    }
  }
  ctx.fillText(line, x, y);
}

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
const maxWidth = 300;
const lineHeight = 24;
const x = (canvas.width - maxWidth) / 2;
const y = 70;
const text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc eu lacinia lorem, eget luctus odio. Pellentesque eget rhoncus eros. Suspendisse a finibus nisl, non porta erat. Donec interdum turpis ac urna egestas tempus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. ';

ctx.font = '15pt Calibri';
ctx.fillStyle = '#555555';
wrapText(ctx, text, x, y, maxWidth, lineHeight);

We create the wrapText function that takes the ctx canvas context.

text is the text to wrap.

x and y are coordinates of the top left corner of the text.

maxWidth is the max width of a line,

And lineHeight is the height of a line of text.

In the function, we split the text with split by a space into an array.

Then we loop through the returned string array entries with the entries method.

Next, we create a line of text with:

const testLine = line + w + ' ';

Next, we call ctx.measureText with testLine to get the dimensions of the text.

Then we have a if statement that checks if testwidth is bigger than maxWidth and index is bigger than 0.

If they’re both true, then we call fillText with the line then we set line to w + ' ' to get the text in the next line.

Then we have y += lineHeight to move the y coordinate of the text for the next line.

Otherwise, we don’t need to wrap the text and we set line to testLine.

Finally, we call ctx.fillText to draw the text.

Next, we get the canvas with querySelector.

Then we get the context with getContext.

And then we set the maxWidth of the text and the lineHeight.

Next, we calculate the x and y values of the top left corner of the text.

Then we set text to a string with the text we want to render.

And then we set the font and fillStyle of the text.

Finally, we call wrapText to draw the text.

Categories
JavaScript Answers

How to Set the Z-index of an HTML5 Canvas with JavaScript?

To set the z-index of an HTML5 canvas with JavaScript, we can use the canvas context’s globalCompositeOperation property.

For instance, we write:

<canvas style='width: 300px; height: 300px'></canvas>

to add a canvas element.

Then we write:

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
let cx = 50;

ctx.globalCompositeOperation = 'destination-over';

const randomColor = () => {
  return ('#' + Math.floor(Math.random() * 16777215).toString(16));
}

const drawCircle = () => {
  ctx.beginPath();
  ctx.arc(cx, 50, 20, 0, Math.PI * 2);
  ctx.closePath();
  ctx.fillStyle = randomColor();
  ctx.fill();
}

for (let i = 0; i < 5; i++) {
  drawCircle();
  cx += 20;
}

We get the canvas element with document.querySelector.

Then we call getContext to get the context.

Then we set globalCompositionOperator to 'destination-over' to draw the new shape behind the current shapes.

Next, we create the randomColor function to return a random color code.

Then we create the drawCircle function that calls ctx.arc to draw a circle.

The first 2 arguments are x and y coordinates of the center. The 3rd argument is the radius.

And the last argument is the angle of the arc, which is Math.PI * 2 since we want to draw a circle.

We call closePath to draw the arc.

fillStyle is the color of the circle.

And we call fill to fill the circle with the fill color.

Finally, we use the for loop to draw 5 circles.

Now we should see that the ones that are drawn later are behind the ones that are drawn earlier.