Categories
JavaScript Answers

How to Remove Zero-Width Space Characters from a JavaScript String?

Sometimes, we want to remove zero-width space characters from a JavaScript string.

In this article, we’ll look at how to remove zero-width space characters from a JavaScript string.

Remove Zero-Width Space Characters from a JavaScript String

To remove zero-width space characters from a JavaScript string, we can use the JavaScript string replace method that matches all zero-width characters and replace them with empty strings.

Zero-width characters in Unicode includes:

  • U+200B zero width space
  • U+200C zero-width non-joiner Unicode code point
  • U+200D zero width joiner Unicode code point
  • U+FEFF zero-width no-break space Unicode code point

For instance, we can do the replacement by writing:

const userInput = 'au200Bbu200Ccu200DduFEFFe';
console.log(userInput.length);
const result = userInput.replace(/[u200B-u200DuFEFF]/g, '');
console.log(result.length);

We have the userInput string that has the zero-width characters listed.

From the first console log, we see userInput.length is 9.

Then we call replace with a regex that matches the zero-width characters listed and replaces them all with empty strings.

And so we see that result.length is 5, so the zero-width characters were removed.

Conclusion

To remove zero-width space characters from a JavaScript string, we can use the JavaScript string replace method that matches all zero-width characters and replaces them with empty strings.

Categories
JavaScript Answers

How to Fetch an Array of URLs with the Promise.all Method in JavaScript?

Sometimes, we want to fetch an array of URLs with the Promise.all method in JavaScript.

In this article, we’ll look at how to fetch an array of URLs with the Promise.all method in JavaScript.

Fetch an Array of URLs with the Promise.all Method in JavaScript

To fetch an array of URLs with the Promise.all method, we can call map to map an array of URLs to promises that fetch the data from the URLs.

Then we can call Promise.all on the array of promises.

For instance, we can write:

const fetchAll = async (urls) => {
  const res = await Promise.all(urls.map(u => fetch(u)))
  const jsons = await Promise.all(res.map(r => r.json()))
  console.log(jsons)
}

const urls = [
  'https://yesno.wtf/api',
  'https://yesno.wtf/api',
  'https://yesno.wtf/api'
]
fetchAll(urls)

to create the fetchAll function that takes an array of urls .

Then we call urls.map with a callback that returns promises returned by fetch for the URL u .

Then we call Promise.all on the array to return a promise with an array of response objects and assign it to res .

Next, we call res.map with a callback that return the JSON response object with the r.json method.

And then we call Promise.all on that to return a promise with the response JSON objects.

Therefore, jsons is something like:

[
  {
    "answer": "yes",
    "forced": false,
    "image": "https://yesno.wtf/assets/yes/10-271c872c91cd72c1e38e72d2f8eda676.gif"
  },
  {
    "answer": "yes",
    "forced": false,
    "image": "https://yesno.wtf/assets/yes/11-a23cbde4ae018bbda812d2d8b2b8fc6c.gif"
  },
  {
    "answer": "yes",
    "forced": false,
    "image": "https://yesno.wtf/assets/yes/0-c44a7789d54cbdcad867fb7845ff03ae.gif"
  }
]

since we called with 3 URL strings in the urls array.

Conclusion

To fetch an array of URLs with the Promise.all method in JavaScript, we can call map to map an array of URLs to promises that fetch the data from the URLs.

Then we can call Promise.all on the array of promises.

Categories
JavaScript Answers jQuery

How to Get All HTML Element IDs with JavaScript?

Sometimes, we want to get all HTML element IDs with JavaScript.

In this article, we’ll look at how to get all HTML element IDs with JavaScript.

Get All HTML Element IDs with JavaScript

To get all HTML element IDs with JavaScript, we just have to select all the elements and then we can get the id property from each element.

For instance, if we have the following HTML:

<div id="mydiv">
  <span id='span1'></span>
  <span id='span2'></span>
</div>

Then we can get the IDs of all the span elements by writing:

const ids = [...$("#mydiv").find("span")].map(s => s.id);
console.log(ids)

We get all the spans with:

$("#mydiv").find("span")

Then we convert the returned nodelist into an array with the spread operator.

And then we call the JavaScript array map method it the returned array with a callback that returns the id from the s span element.

Therefore ids is [“span1”, “span2”] .

Conclusion

To get all HTML element IDs with JavaScript, we just have to select all the elements and then we can get the id property from each element.

Categories
JavaScript Answers

How to Get the Caret Index Position of a contentEditable Element with JavaScript?

Sometimes, we want to get the caret index position of a contentEditable element with JavaScript.

In this article, we’ll look at how to get the caret index position of a contentEditable element with JavaScript.

Use the document.getSelector Method

We can use the document.getSelector to get the selection.

And then we can use that to get the length of the selection to get the cursor position.

For instance, we can write the following HTML:

<div contenteditable>some text here <i>italic text here</i> some other text here <b>bold text here</b> end of text</div>

Then we can write the following JavaScript code to get the location of the cursor by writing:

const cursorPosition = () => {
  const sel = document.getSelection();
  sel.modify("extend", "backward", "paragraphboundary");
  const pos = sel.toString().length;
  if (sel.anchorNode != undefined) sel.collapseToEnd();
  return pos;
}

const elm = document.querySelector('[contenteditable]');

const printCaretPosition = () => {
  console.log(cursorPosition(), 'length:', elm.textContent.trim().length)
}
elm.addEventListener('click', printCaretPosition)
elm.addEventListener('keydown', printCaretPosition)

We have the cursorPosition function that calls the documebnt.getSelection method to get the text inside the div.

Then we call modify to adjust the current selection.

We move 'backward' by 'paragraphboundary' .

Then we get the length of the selection after converting it to a string.

And then we collapse the selection and return pos to return the position of the cursor.

Next, we get the div with querySelector .

And then we create the printCaretPosition to print the cursor position.

Finally, we call addEventListener so that we call printCaretPosition when we click or type on the div.

Conclusion

We can use the document.getSelector to get the selection.

Categories
JavaScript Answers

How to Remove Multiple Elements from an Array in JavaScript?

Sometimes, we want to remove multiple elements from a JavaScript array.

In this article, we’ll look at how to remove multiple elements from a JavaScript array.

Use a for-of Loop

One way to remove multiple elements from a JavaScript array is to use a for -of loop.

For instance, we can write:

const valuesArr = ["v1", "v2", "v3", "v4", "v5"],
  removeValFromIndex = [0, 2, 4];

for (const i of removeValFromIndex.reverse()) {
  valuesArr.splice(i, 1);
}
console.log(valuesArr)

We have the valuesArr with the items we want to remove.

removeValFromIndex has the indexes with the indexes of valuesArr that we want to remove.

Then we loop through the removeValFromIndex backwards with reverse and the for-of loop and remove each item with splice .

We’ve to loop backwards so that we won’t mess up the indexes for items that are yet to be removed.

Therefore, valuesArr is [“v2”, “v4”] .

Use Array.prototype.filter

Also, we can use the JavaScript array filter method to remove items from the array given the indexes of the items we want to remove.

For instance, we can write:

const valuesArr = ["v1", "v2", "v3", "v4", "v5"],
  removeValFromIndex = [0, 2, 4];

const filtered = valuesArr.filter((value, index) => {
  return !removeValFromIndex.includes(index);
})
console.log(filtered)

We call filter with a callback that has the index parameter as the 2nd parameter.

Then we call includes with index to see if the index isn’t in removeValFromIndex .

If it’s not, then we keep the item with the given index in the returned array.

Therefore, filtered is [“v2”, “v4”] .

Conclusion

One way to remove multiple elements from a JavaScript array is to use a for -of loop.

Also, we can use the JavaScript array filter method to remove items from the array given the indexes of the items we want to remove.