Determine the true size of a string, similar to how we measure with a ruler

My goal is to determine the amount of time it takes for the caret to move from the beginning to the end of a string.

Explanation:
Consider this string "" in the following code snippet: http://jsfiddle.net/RFuQ3/
If you place the caret before the first quote and press the right arrow key , you will need to press 3 times to reach after the second quote (instead of 2 times for an empty string).

The most common way to calculate the length of a string is using <string>.length.
However, in this case, it returns 2.

Another method, as discussed here JavaScript Get real length of a string (without entities), also gives a result of 2.

How can I achieve a result of 1?


1-I have come up with an idea to input the string into a text field and then use a while loop with a try{setCaret}catch(){} function.
2-This is simply for entertainment purposes

Answer №1

The symbol in your query "󠀁" corresponds to the Unicode Character 'LANGUAGE TAG' (U+E0001).

Referencing the following inquiries on Stack Overflow,

  • " Embedded UTF-16 unicode characters and JavaScript"
  • " Identifying multibyte character presence in Javascript?"

We gather that

JavaScript strings are UCS-2 encoded however, they can depict Unicode code points beyond the Basic Multilingual Plane (U+0000-U+D7FF and U+E000-U+FFFF) utilizing two 16-bit numbers (a UTF-16 surrogate pair), with the initial number falling within the range of U+D800-U+DFFF.

The UTF-16 surrogate pair representing "󠀁" is U+DB40 and U+DC01. Represented as decimals, U+DB40 is 56128, while U+DC01 is 56321.

console.log("".length); // 2
console.log("".charCodeAt(0)); // 56128
console.log("".charCodeAt(1)); // 56321
console.log("\uDB40\uDC01" === ""); // true
console.log(String.fromCharCode(0xDB40, 0xDC01) === ""); // true

Incorporating code adaptation from , we simply need to tally the total number of code points to reach the correct conclusion:

var getNumCodePoints = function(str) {
    var numCodePoints = 0;
    for (var i = 0; i < str.length; i++) {
        var charCode = str.charCodeAt(i);
        if ((charCode & 0xF800) == 0xD800) {
            i++;
        }
        numCodePoints++;
    }
    return numCodePoints;
};

console.log(getNumCodePoints("")); // 1

jsFiddle Demo

Answer №2

function calculateLength(inputString) {
    let count = 1;
    while (inputString.substring(count,count+1) != "") count++;
    return (count-1);
}

Haven't tested the code yet, but I believe it should function correctly.

Answer №3

Unicode is not fully supported in Javascript, but there's a workaround you can try:

yourstring.replace(/[\uD800-\uDFFF]{2}/g, "0").length

It may be helpful for your needs.

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

Make the pie charts created by progressbar.js larger by increasing their width and height

I have implemented an animated pie chart using the jQuery-plugin-progressbar found at https://github.com/yxfanxiao/jQuery-plugin-progressbar with the following code snippets: JS: ; (function ($) { $.fn.loading = function () { var DEFAULTS ...

Troubleshooting a VueJS Problem: Updating $data in the mounted hook

Revision This snippet of Component.vue was extracted from a larger web application where I made a mistake that had significant consequences, all because of a small change I didn't initially notice. An important distinction exists between the followi ...

Issue with triggering ReactJS onClick function accurately

For the function to work correctly, I had to add e.preventDefault(). However, my goal is for it to redirect the user to '/' after submitting the form. Below is the function that I am attempting to trigger: onAddPoints = (e) => { e.prevent ...

Successfully submitting form_with without experiencing any errors for mandatory fields

I am currently dealing with a form that triggers a sidekiq worker upon submission. The issue I am facing is that even if the form is empty, clicking submit still attempts to run the worker. What I would like is for an alert to notify the user that the fiel ...

Modifying the label focus does not alter the CSS style

I'm struggling with a simple form where I want to highlight the focused labels by changing their background colors. However, the jquery code doesn't seem to be working as expected. Despite no errors showing up in the console, the functionality is ...

The enigmatic void nestled amidst two dividers

I designed a layout with two buttons beside a progress bar, where the buttons are enclosed within a <div> element: <div class="block"> <div class="progress progress-striped active"> <div class="progress-bar" role="progress ...

Dynamic parameters can be passed in Rails using the link_to method

Feeling a bit stuck, maybe this is just a simple question. I have a sort button that I need to use to organize my list of questions. To do this, I create a link_to like this: <%= link_to xx_path(:is_sort => true, :remote=> true , :method=> :p ...

Is it possible to transfer a child from one parent to another using JavaScript?

I need help with moving an element from one parent to another using JavaScript, preferably using the jQuery library. Original code: <div id = "div1"> <p id = "paragraph"> Lorem ipsum dolor sit amet, adipiscing pellentesque egestas. &l ...

How come I am able to send back several elements in react without the need to enclose them in a fragment

This piece of code is functioning properly in React, displaying all the names on the page. However, I am questioning why it is returning multiple elements as a React component. Shouldn't they be wrapped in a single fragment? function App() { const n ...

What is the best way to conduct synchronous testing of animations in AngularJS version 1.3.15?

Encountering a migration issue with angular-animate.js while transitioning from version 1.2 to 1.3. Here is the animation code snippet: 'use strict'; angular.module('cookbook', ['ngAnimate']) .animation('.slide-down& ...

Fade in elements individually with the jQuery Waypoints plugin

I am currently using the waypoints jQuery plugin and it is functioning perfectly when fading in on scroll. However, I am facing an issue with making the blocks fade in individually one after the other. Here is the snippet of my jQuery code: $('.hbloc ...

Redux: Double rendering issue in mapStateToProps

I've recently delved into learning Redux, and I've encountered an issue that's been on my mind. import React, { useEffect } from "react"; import { connect, useDispatch } from "react-redux"; import Modal from "../Moda ...

Struggling to access values from your model using EL in JavaScript? Let me provide some guidance

In my model, there is an object named "domain" with two methods: getDescriptionEn() and getDescriptionFr(). I am trying to retrieve the appropriate description based on the current locale. My issue lies in the following code snippet: var locale = "${cur ...

Having trouble dismissing Bootstrap alerts in TypeScript?

There seems to be an issue with the close button in a simple piece of code. The alert is displayed correctly, but clicking on the close button doesn't close the alert. Currently, I am using bootstrap 5.2.3. My code consists of a basic main file and an ...

Client-side validation with Jquery is failing to function properly

Currently, I am experimenting with the jquery.validate.unobtrusive.js plugin to dynamically generate form fields. Here is an example of how I'm creating a textarea field: var message = $("<textarea id='test'></textarea>"); $(mes ...

Utilizing an undefined constant in angular programming may lead to unexpected errors

Seeking assistance in generating random first and last names based on gender for a form using Angular. I am relatively new to Angular and keep encountering this error whenever the Use of undefined constant firstName - assumed 'firstName' Here ...

SSL-enabled Websocket server powered by websocket.io

I have built a basic Websocket server using node.js and websocket.io var ws = require('websocket.io') , server = ws.listen(8000); server.on('connection', function (socket) { console.log("connected"); socket.on('message&ap ...

It seems that in Laravel 5.3, it's challenging to add a script to a view for an autocomplete

Currently, I am working with Laravel 5.3 for my internship. However, I have encountered a frustrating issue that I need help with: I am trying to implement an "autocomplete" field on a page, but it doesn't seem to be functioning correctly. The error ...

Using the ES6 object spread operator in the JSX syntax of ReactJS

// modules/NavLink.js import React from 'react' import { Link } from 'react-router' export default React.createClass({ render() { //for example this.props={from: "home", to: "about"} return <Link {...this.props} a ...

What is the method to access a form using jQuery? How can I extract the percentage symbol "%" from the entered amount?

I am working on developing a fee calculator using jQuery. In order to achieve this, I need to access forms. Here is the code I have so far: <form id="fee"> <input type="text" title="fee" placeholder="Place the amount that you would like to se ...