PDA

View Full Version : Trying to truncate a string in JQuery



denhamd2
11-20-2008, 05:49 PM
Hi,

I have the following code:

<div class="person">John S</div>

Is is possible in JQuery to remove the last letter of the text within the div class "person"?

I'm banging my head off a brick wall trying to figure this out, any help would be greatly appreciated.

Thanks in advance

jscheuer1
11-21-2008, 03:30 AM
Using the class attribute to select the element may not be the best method, but that depends upon a number of things, and can be fine in certain cases, also depending upon a number of things. Anyways:


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.pack.js"></script>
</head>
<body>
<div class="person">John S</div>
<script type="text/javascript">
$('.person').text($('.person').text().replace(/.$/, ''));
</script>
</body>
</html>

denhamd2
11-21-2008, 11:16 AM
Something strange is happening, I have 3 <div>'s with this class on it and after applying the code each div now contains the 3 people's names with only the last name with the surname removed. Any ideas on where I might be going wrong?

Twey
11-21-2008, 11:57 AM
Well, what did you expect to happen? Isn't this what you wanted?
after applying the code each div now contains the 3 people's names with only the last name with the surname removed.Considering that 'last name' and 'surname' are synonyms, this is quite an interesting problem description. Very Zen.

jscheuer1
11-21-2008, 12:42 PM
I told you class was a tricky way to get the element. I think you want:


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.pack.js"></script>
</head>
<body>
<div class="person">John S</div>
<div class="person">Bob Y</div>
<div class="person">Sally Q</div>
<script type="text/javascript">
$.each( $('.person'), function(i, p){$(p).text($(p).text().replace(/.$/, ''))});
</script>
</body>
</html>

Though there is a more native each (specific to jQuery objects only) that might work better (faster):


$('.person').each(function(){$(this).text($(this).text().replace(/.$/, ''))});