I'm trying to split a word like September 4 down to Sep 4 and I'm not sure how I'd go about that.
The dom I'm trying to edit looks like this:
<div>
<p>September 1</p>
</div>
<div>
<p>Date</p>
<p>September 2</p>
</div>
<div>
<p>Date</p>
<p>September 3</p>
</div>
<div>
<p>Date</p>
<p>September 4</p>
</div>
I figure I can edit the p tag I want by doing: $("div p:nth-child(2)").text() but I'm not sure how to trim the first word to just 3 characters.. Any ideas? Thanks
You can define a function that processes the current text in your p-element and let it return the modified text. It would look something like this:
$("div p:nth-child(2)").text(function(i, oldtext) {
var splitArray = oldtext.split(" ");
return splitArray[0].substr(0,3) + " " + splitArray[1];
});
Here is how you can do that, split the words into an array (separate by space), then remove the characters off the first word, finally join the array again and add the spaces back:
function trimFirstWord(text, amount) {
var wordArray = text.split(" ");
wordArray[0] = wordArray[0].substring(0, amount);
wordArray = wordArray.join(" ");
return wordArray;
}
// Will be "Sep 4"
var newText = trimFirstWord("September 4", 3);
Then here is how you would implement that with .text():
$("div p:nth-child(2)").text(function(){
return trimFirstWord($(this).text(), 3)
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With