pre_replace vs str.replace

Hi there,

I would like to truncate string avoiding cutting off words

in php I could use something like:

if (strlen($description) > $maxchars){
	$smalldesc = substr($description, ' ', $maxchars);
	$smalldesc = preg_replace('/ [^ ]*$/', '...', $smalldesc);
}

I do however need to make this work in js (and I am only starting to learn js)

my script looks like this so far:

if (document.adminForm.description.value!=""){
	if (document.adminForm.description.value.length>=($maxchars-3)){
		document.adminForm.smalldesc.value=document.adminForm.description.value.substr(0,$maxchars-3) + "...";
	} else {
		document.adminForm.smalldesc.value=document.adminForm.description.value;
	}
} else {
	document.adminForm.smalldesc.value="";
}

trying to adjust that to reflect the functionality in the php snippet doesn’t work

if (document.adminForm.description.value!=""){
	if (document.adminForm.description.value.length>=($maxchars-3)){
		document.adminForm.smalldesc.value=document.adminForm.description.value.substr(0,$maxchars-3);
		document.adminForm.smalldesc.value=str.replace(/ [^ ]*$/, document.adminForm.smalldesc.value)+ "...";
	} else {
		document.adminForm.smalldesc.value=document.adminForm.description.value;
	}
} else {
	document.adminForm.smalldesc.value="";
}

could somebody please point out to me how to get this to work?

positively so! works like a charm! thanks bunches! - also for the hints :slight_smile:

would you mind an explanation of the difference between the substring and the substr methods ? the results appear to being identical.

thanks again for the clarification!

Something like this?


var form = document.adminForm,
    description = form.elements.description,
    smallDesc = '';
if (description.value > '') {
    if (description.value.length >= $maxchars - 3) {
        smallDesc = description.value.substring(0, $maxchars)
            .split(' ') // divide up into separate words
            .slice(0, -1) // remove the last (partial) word
            .join(' ') // reform in to a string
            + '...'; // add on ellipses
    }
}
form.elements.smalldesc.value = smallDesc;

substring uses values that indicate the start and stop position.
substr uses the start position and length instead.