views:

253

answers:

5

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.

+12  A: 

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?

Prot0
The *if* statement is optional here. *str.substring(0,10)* on a string with less than 10 characters would remain unaffected :)
Andy E
but the if statement can be used to something like:{var str = 'Some very long string';if(str.length > 10) str = str.substring(0,10)+"...";}
Daniel Persson
@Daniel: true, it would be necessary for adding an ellipsis. Luckily I used the word *optional* :-)
Andy E
@Daniel, "if(str.length > 10) str = str.substring(0,10)+"..."; }" is wrong because the resultstring has a length of 13 not 10 !! correct: "if(str.length > 10) str = str.substring(0,10-3)+"..."; }"
Floyd
+3  A: 

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);
sje397
*.text()* is more appropriate than *.html()* when dealing with text only.
Andy E
Nasir
@Nasir - you can change the arguments to substr...or you might want to look at regular expressions.
sje397
@Nasir - check update
sje397
A: 

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.

Giu
Hi Giu,I am not dealing with the text when it is being input...rather when it gets displayed and break my table layout. The querystring text is displayed in a DIV called .tasks-overflow
Nasir
@Nasir Thanks for the hint; I've updated my answer; it should help you solve your little issue
Giu
Hi Giu,I've tried your code and it hasn't worked.I want this long string 'thisisonelooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooongquerystring' to display as 'thisisonelooo...'
Nasir
This is how the code looks:$(document).ready(function(){ $(".tasks-overflow:contains('http://')").each(function(){ var self = $(this) , txt = self.text(); txt = txt.replace(/(http[s]*:[\/\\]{2})[^\s]*/g,'$1...'); self.text(txt); });//Giu code var elem = $(".tasks-overflow"); if(elem){ if (elem.val().length > 10) elem.val(elem.val().substr(0,10)) } });
Nasir
@Nasir I'm sorry; my old answer contained the `val` method, which doesn't seem to work for DIV elements. I've updated my answer again, and now the `text` method is used to alter the text, which should work perfectly (tested it locally, again). Could you please test it again with my updated code and let me know?
Giu
Nasir
@Nasir You could use the following RegExp to filter out / replace your string, assuming that it only consists of letters: `/[a-zA-Z]{10}/`
Giu
@Giu how would I go about implementing a RegExp?
Nasir
A: 

What you should also do when you truncate the string to ten characters is add the actual html ellipses entity: &hellip;, rather than three periods.

Ken Ray
+1  A: 

Hi Nasir,
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

pferdefleisch
+1 - i was looking for a way to use replace :)
sje397