The character count displayed is 497 instead of 562 because of Unicode; what is the correct way to determine the actual length?

Displayed below is a string with a length of 497, although it actually contains 562 characters:

alert('[**BFI/KBFI**](http://aviationweather.gov/adds/metars/?station_ids=KBFI&std_trans=translated&chk_metars=on&hoursStr=most+recent+only&chk_tafs=on&submitmet=Submit): Boeing Field King County International Airport \u2022 **Observed:** 55 mins ago \u2022 **Wind:** 170\u00B0/S @ 12 kts \u2022 **Visibility:** 10.0mi/16.09km \u2022 **Sky (AGL):** Few clouds @ 1,800ft; Broken clouds @ 2,600ft; Overcast @ 3,600ft \u2022 **Temperature:** 10.6\u00B0C/51\u00B0F \u2022 **Dewpoint:** 6.7\u00B0C/44\u00B0F \u2022 **Pressure:** 29.70" Hg/1,006mb \u2022 **Conditions:** MVFR'.length);

A discrepancy of 65 characters can be observed, likely due to the presence of Unicode characters such as the degrees symbol \u00B0.

I require the outputted length to display total character literals; how may I rectify this issue?

The aforementioned string can be accessed on JSFiddle.

Answer №1

The size is 497. As your code processes it, the string literal is decrypted long in advance. The stored string representation in memory includes those Unicode characters.

To have symbols like \u00b0 read as they are, make sure to escape the backslash with another backslash.

Answer №2

Imagine you have a string with some unique Unicode characters. When passing this string to another code, it gets represented using \u escapes. However, this new representation is deemed too long and rejected due to counting the escapes.

Simply asking the Javascript interpreter for the 'length' won't solve this issue because at that moment, the Unicode characters are considered single characters. The real length is only known once the code expands into a representation with escapes.

A clever suggestion from a commenter was to use JSON.stringify(str).length as a close enough approximation in such cases.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Would this code effectively disable the right-clicking menu for MathJax?

My current approach involves utilizing the following code snippet: <script type="tet/x-mathjax-config"> MathJax.Hub.Config({ showMathMenu: false }); </script> I intended for this code to disable the right-click menu on my math webs ...

I am looking to retrieve products based on category alone, category and model together, or simply obtain all products in one go. At the moment, I am utilizing three distinct endpoints

I have 3 endpoints on my backend that fetch products based on certain criteria. I'm considering whether to refactor the logic and combine them into a single endpoint/function. Currently, my routes are structured as follows: router.get('/products& ...

Discover the magic of triggering events that dynamically alter CSS styles

I am trying to implement an eventBus in the App.vue component that allows me to change a modal's CSS based on a payload object. For example, if I pass { type: 'success' }, the border of the modal should turn green, and if I pass { type: &apo ...

Creating Twillio access codes with NodeJS

As I work on a project integrating Twillios Programmable Video API, I find myself navigating through the Node JS documentation for the first time. It's been quite clear so far, but I do have a couple of lingering questions. Below is the code snippet ...

jQuery trigger event when a DropDownList/SELECT item is selected

My current jQuery code filters a list of links on the page by firing when a link with a specified href is clicked. The id of the link determines which content remains visible. Here's an example: <script type="text/javascript"> $(docume ...

Display a loading screen in ExpressJS until the data is fully loaded and ready for use

I am currently utilizing puppeteer to extract data from a job website, and so far everything is running smoothly. app.get('/', async (req, res) => { res.render('index', {text: 'This is the index page'}); }) Up ...

What is causing the breakdown in communication between my server and client?

While utilizing React and an Express server for the backend, I am facing an issue where my API call to server.js is not going through. The React client is running on port 3001 and the server on port 3002. The fetch code in CreateAccount.js is as follows: ...

Retrieve the link of a nearby element

My goal is to create a userscript that has the following functionalities: Add a checkbox next to each hyperlink When the checkbox is clicked, change the state of the corresponding hyperlink to "visited" by changing its color from blue to violet. However ...

A guide to extracting row and column information from tables using div tags

I need assistance with extracting data from rows and columns that are represented by div tags within a table. This table does not use traditional tbody, tr, and td tags but instead presents the data in a UI grid view using div tags. Can anyone provide gu ...

Display a visual progress indicator during audio recording

I am currently using the MediaRecorder functionality to capture audio and I would like to display a progress bar showing the recording process. Here is the code snippet from my recorder template: <p id="countdowntimer">Current Status: Beginning in& ...

How to Extract Minutes in Datatables Timestamps and Apply Custom Styling

Working with Datatables v1.10 Right now, my table is showing a date in the second column in the format 17-04-2019 14:34, which is how it's stored in the database. The filtering and searching functionality are all working as expected. The current HTM ...

React - Issue with updating state within a Promise callback

Trying to update the state within a then() block of a Promise is proving difficult, as the value is not persisting and remains inaccessible outside of that specific block. The following is the code snippet with recent modifications: handleSelect = locati ...

Guide to comparing two TSX elements in a React + TSX environment

I am facing difficulties in comparing two React TSX elements. Despite being new to both React and TSX, I have tried copying and pasting the exact elements for comparison but it doesn't seem to work. Can you guide me on what might be causing this issue ...

provide a counter to an unnamed function

I have a simple question - how can I pass a unique value to an anonymous function? Perhaps I should rephrase it... what I am asking is, take a look at the following code snippet... let's say I have several clickable items with IDs like somediv1, some ...

Is it possible to implement AngularJS Routing for displaying HTML pages within a slideshow?

I have a vision for my website in mind - a stunning slideshow with a sleek navigation bar at the top. The idea is to have each slide represent a different category or concept, all uniquely customized with their own HTML page. However, I'm facing a cha ...

React Three Fiber - THREE.BufferGeometry.computeBoundingSphere(): The calculated radius is invalid. It is possible that the "position" attribute contains NaN values causing this issue

Currently, I am working on a website using Reactjs and React Three Fiber for 3D components. Out of the total 3 3D components, 2 are functioning properly. However, one of them suddenly stopped working more than 6 hours ago, and I have been unable to find a ...

The node server is not receiving the request for updating the src file to an image element

Uncertainty looms over whether this issue stems from a node-related problem or if there is a gap in my foundational understanding. Consider the following snippet of JQuery: $('#someimgId').attr('src','/images/somefile.jpg'); ...

Having trouble setting the backgroundImage in React?

Hi there! I'm in the process of crafting my portfolio website. My goal is to have a captivating background image on the main page, and once users navigate to other sections of the portfolio, I'd like the background to switch to a solid color. Alt ...

How come the state isn't being updated in React when calling setState() repeatedly?

After starting my learning journey with React by using the official documentation, I came across this interesting note: "React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asyn ...

What techniques can I use to achieve a seamless transition using Javascript and CSS?

I'm striving for a seamless CSS transition. The concept of transition had me puzzled. Even though I utilized the setTimeout method in JavaScript to make my CSS functional, it lacks that SMOOTH feel! Check out my code below. function slideChange( ...