0

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");

    });
});
Josh Bedo
  • 3,410
  • 3
  • 21
  • 33
  • 3
    possible duplicate of [javascript shorten string without cutting words](http://stackoverflow.com/questions/5454235/javascript-shorten-string-without-cutting-words) – Pointy Mar 28 '11 at 20:23
  • yes, i wasnt sure how to delete the other topic it wasn't as descriptive as this one and had no code. – Josh Bedo Mar 28 '11 at 21:04

2 Answers2

0

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));
Oliver Moran
  • 5,137
  • 4
  • 31
  • 45
0

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

Mark Costello
  • 4,334
  • 4
  • 23
  • 26
  • i was trying to use new RegExp but i must've been doing it wrong. – Josh Bedo Mar 28 '11 at 21:05
  • See it doesn't work with my div im not sure why http://jsfiddle.net/Yc3mf/1/ might've figured out the problem for some reason the text had to be in front of the

    tag and couldn't be on the line below same with closing tag heres example http://jsfiddle.net/Yc3mf/3/

    – Josh Bedo Mar 28 '11 at 21:09
  • This is the regular expression you want. It'll ignore the whitespace and new line characters before the paragraph content. `new RegExp('^[\\s]*(.{' + maxLength + '}[^\\s]*).*')` @josh – Mark Costello Mar 29 '11 at 13:47