Skip to content Skip to sidebar Skip to footer

Trimming A String Within A Div

product name
When I calculate the length of the string of product name using the following code: var productnames = document.getElementsByCl

Solution 1:

If you're using jQuery plugin. Its simpler than that.

$.trim(stringHere);

So your code would be

$.trim($('.name').text());

In the code, the $('.name').text() would be the string provided to the method which has to be trimmed down. I have created an example fiddle for you to check how it works.

http://jsfiddle.net/afzaal_ahmad_zeeshan/dJ9SA/

For more: http://api.jquery.com/jQuery.trim/

Solution 2:

I think you're already there:

var productnames = document.getElementsByClassName('name'),
    html = productnames[0].innerHTML.trim(), // returns the trimmed string
    len = html.length; // gets the length of the stringconsole.log(html); // "product name"console.log(len);` // 12

Post a Comment for "Trimming A String Within A Div"