How do I get a long text string (like a querystring) to display a maximum of 10 characters, using JQuery?
Sorry guys I'm a novice at JavaScript & JQuery :S
Any help would be greatly appreciated.
If I understand correctly you want to limit a string to 10 characters?
var str = 'Some very long string';
if(str.length > 10) str = str.substring(0,10);
Something like that?
Creating own answer, as nobody has considered that the split might not happened (shorter text). In that case we don't want to add '...' as suffix.
Ternary operator will sort that out:
var text = "blahalhahkanhklanlkanhlanlanhak";
var count = 35;
var result = text.slice(0, count) + (text.length > count ? "..." : "");
Can be closed to function:
function fn(text, count){
return text.slice(0, count) + (text.length > count ? "..." : "");
}
console.log(fn("aognaglkanglnagln", 10));
And expand to helpers class so You can even choose if You want the dots or not:
function fn(text, count, insertDots){
return text.slice(0, count) + (((text.length > count) && insertDots) ? "..." : "");
}
console.log(fn("aognaglkanglnagln", 10, true));
console.log(fn("aognaglkanglnagln", 10, false));
var example = "I am too long string";
var result;
// Slice is JS function
result = example.slice(0, 10)+'...'; //if you need dots after the string you can add
Result variable contains "I am too l..."
And here's a jQuery example:
HTML text field:
<input type="text" id="myTextfield" />
jQuery code to limit its size:
var elem = $("#myTextfield");
if(elem) elem.val(elem.val().substr(0,10));
As an example, you could use the jQuery code above to restrict the user from entering more than 10 characters while he's typing; the following code snippet does exactly this:
$(document).ready(function() {
var elem = $("#myTextfield");
if (elem) {
elem.keydown(function() {
if (elem.val().length > 10)
elem.val(elem.val().substr(0, 10));
});
}
});
Update:
The above code snippet was only used to show an example usage.
The following code snippet will handle you issue with the DIV element:
$(document).ready(function() {
var elem = $(".tasks-overflow");
if(elem){
if (elem.text().length > 10)
elem.text(elem.text().substr(0,10))
}
});
Please note that I'm using text instead of val in this case, since the val method doesn't seem to work with the DIV element.
('very long string'.slice(0,10))+'...'
// "very long ..."
html
<p id='longText'>Some very very very very very very very very very very very long string</p>
javascript (on doc ready)
var longText = $('#longText');
longText.text(longText.text().substr(0, 10));
If you have multiple words in the text, and want each to be limited to at most 10 chars, you could do:
var longText = $('#longText');
var text = longText.text();
var regex = /\w{11}\w*/, match;
while(match = regex.exec(text)) {
text = text.replace(match[0], match[0].substr(0, 10));
}
longText.text(text);
What you should also do when you truncate the string to ten characters is add the actual html ellipses entity: …, rather than three periods.
Although this won't limit the string to exactly 10 characters, why not let the browser do the work for you with CSS:
.no-overflow {
white-space: no-wrap;
text-overflow: ellipsis;
overflow: hidden;
}
and then for the table cell that contains the string add the above class and set the maximum permitted width. The result should end up looking better than anything done based on measuring the string length.
A = "a lennnnnnnnnnnnngthy string ";
word = A.substring(0, number_of_words_to_appear) + "...";
console.log(word)
This looks more to me like what you probably want.
$(document).ready(function(){
var stringWithShorterURLs = getReplacementString($(".tasks-overflow").text());
function getReplacementString(str){
return str.replace(/(https?\:\/\/[^\s]*)/gi,function(match){
return match.substring(0,10) + "..."
});
}});
you give it your html element in the first line and then it takes the whole text, replaces urls with 10 character long versions and returns it to you.
This seems a little strange to only have 3 of the url characters so I would recommend this if possible.
$(document).ready(function(){
var stringWithShorterURLs = getReplacementString($(".tasks-overflow p").text());
function getReplacementString(str){
return str.replace(/https?\:\/\/([^\s]*)/gi,function(match){
return match.substring(0,10) + "..."
});
}});
which would rip out the http:// or https:// and print up to 10 charaters of www.example.com
Try this :)
var mystring = "How do I get a long text string";
mystring = mystring.substring(0,10);
alert(mystring);
#jolly.exe
Nice example Jolly. I updated your version which limits the character length as opposed to the number of words. I also added setting the title to the real original innerHTML , so users can hover and see what is truncated.
HTML
<div id="stuff">a reallly really really long titleasdfasdfasdfasdfasdfasdfasdfadsf</div>
JS
function cutString(id){
var text = document.getElementById(id).innerHTML;
var charsToCutTo = 30;
if(text.length>charsToCutTo){
var strShort = "";
for(i = 0; i < charsToCutTo; i++){
strShort += text[i];
}
document.getElementById(id).title = "text";
document.getElementById(id).innerHTML = strShort + "...";
}
};
cutString('stuff');
const text = 'imathelongtextblablabla'
const showLess = false
{!showLess && `${text.substring(0, 10)}`}
{!showLess && "..."}
Show this "long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text "
to
long text long text long ...
function cutString(text){
var wordsToCut = 5;
var wordsArray = text.split(" ");
if(wordsArray.length>wordsToCut){
var strShort = "";
for(i = 0; i < wordsToCut; i++){
strShort += wordsArray[i] + " ";
}
return strShort+"...";
}else{
return text;
}
};
Related
I have a long String containing a HTML document. I want to delete all the href Tags but keep the text. The following example:
Some text example 1</p> some example 2text
should become:
Some text example 1 </p> some example 2 text
The solution I found is to get all the textes, and then try to iterate again through the text and replace the tag number n with the text number n.
var a_string = 'Some text example 1</p> some example 2text',
el = document.createElement('p');
el.innerHTML = a_string;
var a = el.querySelectorAll('a');
var texts = [].slice.call(a).map(function(val){
return val.innerHTML;
});
alert(texts);
// TODO ieterate and replace occurence n with texts[n]
Is there a besser way to do this?
After first line write following code
a_string = a_string.replace(/(<a.*?>)/g,'').replace(/<\/a>/g,' ');
You can use the following Regex:
var regex = /(<\s*a([^>]+)>|<\/\s*a\s*>)/ig;
var str = 'Some text example 1</p> some example 2text';
str.replace(regex, ""); //Some text example 1</p> some example 2text
Try below regex:
var a_txt = a_string.replace(/<a[\s]+[^>]*?href[\s]?=[\s\"\']*(.*?)[\"\']*.*?>/g,"").replace(/<\/a>/g," ");
Your solution of query-selecting all a-tags isn't actually too bad. Instead of getting the text with map you could just iterate over the list and replace each element with its content. No need for regular expressions:
el.querySelectorAll('a').forEach(function( a_el ){
var text = document.createTextNode(a_el.innerText);
a_el.parentNode.replaceChild(text, a_el);
});
also, instead of "parsing" your html by putting it into a p-element, you could use a DomParser:
var parser = new DOMParser();
var doc = parser.parseFromString(a_string, "text/html");
doc.querySelectorAll('a').forEach(function( a_el ){
var text = document.createTextNode(a_el.innerText);
a_el.parentNode.replaceChild(text, a_el);
});
as stated in some answer above, your code isn't bad. I avoid the use of regular expression when not necessary.
To finish your code, you neeed to iterate through all A{ELEMENTS}. I am typing from mobile phone. Let me know if you hit an error. Thanks.
var a_string = 'Some text example 1</p> some example 2text',
el = document.createElement('p');
el.innerHTML = a_string;
var a = el.querySelectorAll('a');
for( var t = a.length - 1; t >=0 ; t-- ){
for(var c = a[t].childNodes.length - 1; c >= 0; c-- ){
if( a[t].nextSibling ){
document.insertBefore( a[t].childNodes[c], a[t].nextSibling );
} else {
a[t].parentNode.appendChild( a[t].childNodes[c]);
}
}
a[t].remove();
}
This question already has answers here:
Shorten string without cutting words in JavaScript
(27 answers)
How to trim content of element and put "..." if the characters go over a certain limit?
(3 answers)
Closed 9 years ago.
I have a bunch of title texts that get generated they all have different .Length but at a specific startindex of the string I want to find the closest space and then remove the text after it and also the space, and then add "...".
The most important part is that it shouldnt extend 49 length
Example:
"What can UK learn from Spanish high speed rail when its crap"
I want to make sure that it becomes:
"What can UK learn from Spanish high speed rail..."
How can I do this with Jquery?
I have a C# code that acheive this:
public static string TrimLength(string text, int maxLength)
{
if (text.Length > maxLength)
{
maxLength -= "...".Length;
maxLength = text.Length < maxLength ? text.Length : maxLength;
bool isLastSpace = text[maxLength] == ' ';
string part = text.Substring(0, maxLength);
if (isLastSpace)
return part + "...";
int lastSpaceIndexBeforeMax = part.LastIndexOf(' ');
if (lastSpaceIndexBeforeMax == -1)
return part + "...";
else
return text.Substring(0, lastSpaceIndexBeforeMax) + "...";
}
else
return text;
}
But I have no idea how to do this with jquery
Any kind of help is appreciated or any kind of tips on how to achieve this.
Here's a general Javascript solution to this common task. jQuery isn't necessary but is used for $.trim to keep the input string neat.
var ellipsis = "...";
function TrimLength(text, maxLength)
{
text = $.trim(text);
if (text.length > maxLength)
{
text = text.substring(0, maxLength - ellipsis.length)
return text.substring(0, text.lastIndexOf(" ")) + ellipsis;
}
else
return text;
}
And to test:
sentence = "The quick brown fox jumps over a lazy dog.";
for (var i = 10; i <= 50; i += 10){
console.log(TrimLength(sentence, i));
};
Output:
The...
The quick brown...
The quick brown fox jumps...
The quick brown fox jumps over a...
The quick brown fox jumps over a lazy dog.
> jsFiddle demo
It is also worth noting that you can achieve a similar effect with CSS's text-overflow, which may be better suited to your situation: http://jsfiddle.net/LtQ2j/3/
0, I guess you misunderstood the purpose of jQuery (just read the first paragraph: "What is jQuery?"). jQuery is a framework built on top of javascript to manipulate the DOM in the browser. For what you need you only need a simple javascript expression:
function trimToLen(str, maxLen) {
var trimmed = str.substr(0, maxLen);
return trimmed.substr(0, trimmed.lastIndexOf(' ')) + '…';
}
to make it work for strings shorter than the maxLex you have to add an additional condition:
function trimToLen(str, maxLen) {
if (str.length <= maxLen) {
return str;
}
var trimmed = str.substr(0, maxLen);
return trimmed.substr(0, trimmed.lastIndexOf(' ')) + '…';
}
and now the examples:
trimToLen("too short", 15);
// returns: too short
trimToLen("equal to maxLen", 15);
// returns: equal to maxLen
trimToLen("a little more than maxLen", 15);
// returns: a little more…
Notice that I used … (elipsis) instead of ... (3 x dot). Visually it is is pretty much the same but you save a couple of characters and also avoid complicating the logic with the length of the trimmed text (because you have 3 instead of 1 character).
Another thing you might want is to normalise spaces in order to catch tabs, new lines or spaces. This could be the case when you want to display a longer description (containing formatted text) in one short <a> or <span> tag. For that you can use a simple regex as the first expression in the function:
str = str.replace(/\s/g, ' ');
Just for completeness, you can do slightly better using the 2-arg form of lastIndexOf:
var ellipsis = "...";
function Truncate(text, maxLength)
{
if (text.length <= maxLength)
return text;
maxLength -= ellipsis.length;
var space = text.lastIndexOf(" ", maxLength);
if (space >= 0)
maxLength = space;
return text.slice(0, maxLength) + ellipsis;
}
The problem: I want to get all of the square brackets' content, and then delete them, but only if the brackets are at the beginnig of the string.
For example, a given string [foo][asd][dsa] text text text will return array with all of the three brackets' content (["foo", "asd", "dsa"]), and the string will become text text text.
But if the string looks like that: [foo] text [asd][dsa] text text, it'll take only the [foo], and the string will become: text [asd][dsa] text text.
How can I do that using JavaScript?
The loop checks the start of the string for anything in square brackets, takes the contents of the brackets, and removes the whole lot from the start.
var haystack = "[foo][asd][dsa] text text text";
var needle = /^\[([^\]]+)\](.*)/;
var result = new Array();
while ( needle.test(haystack) ) { /* while it starts with something in [] */
result.push(needle.exec(haystack)[1]); /* get the contents of [] */
haystack = haystack.replace(needle, "$2"); /* remove [] from the start */
}
Something like var newstring = oldstring.replace(/\[\w{3}]/, "");
You could proceed using a while, taking the first, adding it to an array, remove it and then do all again. This would give this :
var t1 = "[foo][asd][dsa] text text text";
var rule = /^(?:\[([^\]]*)\])/g;
var arr = new Array();
while(m = rule.exec(t1)){
arr.push(m[1]);
t1 = t1.replace(rule, "")
}
alert(arr); // foo,asd,dsa
alert(t1); // text text text
I have a text say "A sample text for testing". I need to display only ten characters in a div.
so i do substring on the text
txt.substring(0,10)
This gives me "A sample t". Since its ugly to display a unterminated word, i need only to display "A Sample" to be displayed. How do i do this?
You could do what you do, substringing the text to 10 chars.
Then you use txt.lastIndexOf(' ') to find the last space in the text.
Then you use that to substring the text again.
Example:
var txt = "A Sample Text";
txt = txt.subString(0,10); // "A Sample T"
txt = txt.subString(0, txt.lastIndexOf(' ')); // "A Sample"
Let me know if it helps!
Assuming that you'd rather have a cut off string than an empty string, if the word is longer than ten characters:
function shorten(txt)
{
// if it's short or a space appears after the first 10 characters, keep the substring (simple case)
if (txt.length <= 10 || txt[10] === ' ') return txt;
// get the index of the last space
var i = txt.substring(0, 11).lastIndexOf(' ');
// if a space is found, return the whole words at the start of the string;
// otherwise return just the first 10 characters
return txt.substring(0, i === -1 ? 11 : i);
}
use substring method to do this
i think you should add a filter to check whether the 11th character is space or not with the substring method. otherwise the last valid word too might removed. get "New sample text for testing" for example.
this is the code.
str = "A sample text for testing"
ch11_space = (str[10] == ' ') ? 0 : 1;
str = str.substring(0,10);
if (ch11_space) {
str = str.substring(0,str.lastIndexOf(' '));
}
function getShortenedString(str)
{
var maxLength = 10; // whatever the max string can be
var strLength = str.length;
var shortenedStr = str.substr(0, maxLength);
var shortenedStrLength = shortenedStr.length;
var lastSpace = str.lastIndexOf(" ");
if(shortenedStrLength != strLength)
{
// only need to do manipulation if we have a shortened name
var strDiff = strLength - shortenedStrLength;
var lastSpaceDiff = shortenedStrLength - lastSpace;
if(strDiff > lastSpaceDiff) // non-whole word after space
{
shortenedStr = str.substr(0, lastSpace);
}
}
return shortenedStr;
}
say i had the string text = "this is a long string i cant display" i want to trim it down to 10 characters but if it doesnt end with a space finish the word i don't want the string variable to look like this "this is a long string i cant dis" i want it to finish the word until a space occurs. I'm trying this which was suggested by other people but .replace doesn't seem to be working but .length does? I read somewhere that javascript functions don't work inside jquery functions but i still don't understand why .length works
$(document).ready(function(){
$('.article').each(function(index){
var text = $(this).children('p').text()
var maxLength = 6;
var url = $(this).find('.article-link').attr('href');
alert(text.replace(/^(.{1}[^\s]*).*/, "$1"));
var trimmedString = text.substr(0, maxLength);
var text = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")));
//var text = text.substring(0, 80);
//text = text.replace(/^(.{10}[^\s]*).*/, "$1");
});
});
Seo duit, a chara:
var str = "The rain in Spain falls mainly on the plain.";
var l = 10;
while (str.length > l && str.substr(l-1,1) != " ") l++;
alert(str.substr(0,l));
Javascript functions most definitely do work inside jQuery functions. It looks like your regex might be the issue, if the replace function isn't working for you.
This code works:
$(document).ready(function() {
$('.article').each(function(index) {
var text = $(this).children('p').text();
var maxLength = 6;
var reg = new RegExp('^(.{' + maxLength + '}[^\\s]*).*');
alert(text.replace(reg, "$1"));
});
});
Here's a working example