Categories
JavaScript Answers

How to Extract the Text Out of HTML String Using JavaScript?

To extract the text out of HTML string using JavaScript, we can set the innerHTML property of an element to the HTML string.

Then we can use the textContent or the innerText property to get the text of the element.

For instance, we can write:

const extractContent = (s) => {
  const span = document.createElement('span');
  span.innerHTML = s;
  return span.textContent || span.innerText;
};

console.log(extractContent("<p>Hello</p><a href='http://example.org'>example</a>"))

to create the extractContent function that takes the s HTML string.

In the function, we call document.createElement to create the span element.

Then we set the innerHTML property of the span to s.

And finally, we return the textContent or innerText property to return the text content string.

Therefore, from the console log, we see 'Helloexample' logged.

Categories
JavaScript Answers

How to Find the Last Matching Object in Array of Objects with JavaScript?

To set Letter spacing in canvas element with JavaScript, we can use the JavaScript array’s reverse and fine methods.

For instance, we can write:

const fruits = [{
    shape: 'round',
    name: 'orange'
  },
  {
    shape: 'round',
    name: 'apple'
  },
  {
    shape: 'oblong',
    name: 'zucchini'
  },
  {
    shape: 'oblong',
    name: 'banana'
  },
  {
    shape: 'round',
    name: 'grapefruit'
  }
]
const currentShape = 'round'
const fruit = fruits.slice().reverse().find(fruit => fruit.shape === currentShape);
console.log(fruit)

We have the fruits array.

And we want to find the last element that has the shape property set to 'round'.

To do this, we call fruits.slice to return a copy of the fruits array.

Then we call reverse to reverse the array copy.

And finally, we call find with a callback that checks if fruit.shape is equal to currentShape.

Therefore, fruit is:

{shape: "round", name: "grapefruit"}

as we expect.

Categories
JavaScript Answers

How to Set Letter Spacing in Canvas Element with JavaScript?

To set Letter spacing in canvas element with JavaScript, we can set the canvas element’s style.letterSpacing property.

For instance, we can write:

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

to add the canvas element.

Then, we write:

const can = document.querySelector('canvas');
const ctx = can.getContext('2d');
can.width = can.offsetWidth;
ctx.clearRect(0, 0, can.width, can.height);
can.style.letterSpacing = '10px'
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.font = '4em sans-serif';
ctx.fillText('Hello', can.width / 2, can.height * 1 / 4);

can.style.letterSpacing = '30px'
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.font = '4em sans-serif';
ctx.fillText('World', can.width / 2, can.height * 3 / 4);

to get the canvas with document.querySelector.

Then we get the canvas context with getContext.

Next, we set the can.style.letterSpacing to set the letter spacing we want for our text.

We also, set the textAlign, textBaseline, and font properties to set the font style we want.

Finally, we call fillText to draw the text onto the canvas.

The arguments are the text, width, and height of the text respectively.

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.