Languages
[Edit]
EN

JavaScript - simple way how to write own function to make beauty string shortcuts

2 points
Created by:
JustMike
3488

In this article, we're going to have a look at how to wite in JavaScript own function that creates shortcut for string.

There are available styles to achieve same effect, but sometimes we are not able to do it with styles and we need to have shortcut string e.g canvas string drawing or title / alt attribute.

This approach solves somehow problem of multiline text with ... at the end if we don't want to display all text because css solutions are not enough at this moment (we have 2020).

1. Custom method example

Presented solution in this section tries to find closes white character to cut string in pretty way - to do not split worlds. Only when it is impossible to find white character, function cuts worlds.

// ONLINE-RUNNER:browser;

var Utils = new function() {
    var expression = /\s[^\s]*$/;

    this.createShortcut = function(text, limit) {
        if (text.length > limit) {
            var part = text.slice(0, limit - 3);
            if (part.match(expression)) {
                return part.replace(expression, '...');
            }
            return part + '...';
        }
        return text;
    };
};

// Usage example:

// number:           |10   |16           |30
//                   v     v             v
var text = 'This is example very long text that should be cut.';
// cutting:     |  |                 |

console.log(Utils.createShortcut(text,  10)); // This...
console.log(Utils.createShortcut(text,  16)); // This is...
console.log(Utils.createShortcut(text,  30)); // This is example very long...
console.log(Utils.createShortcut(text, 250)); // This is example very long text that should be cut.

// number:           |10   |16           |30
//                   v     v             v
var text = 'This_is_example_very_long_text_that_should_be_cut.';
// cutting:        |     |             |

console.log(Utils.createShortcut(text,  10)); // This_is...
console.log(Utils.createShortcut(text,  16)); // This_is_examp...
console.log(Utils.createShortcut(text,  30)); // This_is_example_very_long_t...
console.log(Utils.createShortcut(text, 250)); // This is example very long text that should be cut.

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.