How can I trim a text like this with jquery? [duplicate] - javascript

This question already has answers here:
Shorten string without cutting words in JavaScript
(27 answers)
How to trim content of element and put "..." if the characters go over a certain limit?
(3 answers)
Closed 9 years ago.
I have a bunch of title texts that get generated they all have different .Length but at a specific startindex of the string I want to find the closest space and then remove the text after it and also the space, and then add "...".
The most important part is that it shouldnt extend 49 length
Example:
"What can UK learn from Spanish high speed rail when its crap"
I want to make sure that it becomes:
"What can UK learn from Spanish high speed rail..."
How can I do this with Jquery?
I have a C# code that acheive this:
public static string TrimLength(string text, int maxLength)
{
if (text.Length > maxLength)
{
maxLength -= "...".Length;
maxLength = text.Length < maxLength ? text.Length : maxLength;
bool isLastSpace = text[maxLength] == ' ';
string part = text.Substring(0, maxLength);
if (isLastSpace)
return part + "...";
int lastSpaceIndexBeforeMax = part.LastIndexOf(' ');
if (lastSpaceIndexBeforeMax == -1)
return part + "...";
else
return text.Substring(0, lastSpaceIndexBeforeMax) + "...";
}
else
return text;
}
But I have no idea how to do this with jquery
Any kind of help is appreciated or any kind of tips on how to achieve this.

Here's a general Javascript solution to this common task. jQuery isn't necessary but is used for $.trim to keep the input string neat.
var ellipsis = "...";
function TrimLength(text, maxLength)
{
text = $.trim(text);
if (text.length > maxLength)
{
text = text.substring(0, maxLength - ellipsis.length)
return text.substring(0, text.lastIndexOf(" ")) + ellipsis;
}
else
return text;
}
And to test:
sentence = "The quick brown fox jumps over a lazy dog.";
for (var i = 10; i <= 50; i += 10){
console.log(TrimLength(sentence, i));
};
Output:
The...
The quick brown...
The quick brown fox jumps...
The quick brown fox jumps over a...
The quick brown fox jumps over a lazy dog.
> jsFiddle demo
It is also worth noting that you can achieve a similar effect with CSS's text-overflow, which may be better suited to your situation: http://jsfiddle.net/LtQ2j/3/

0, I guess you misunderstood the purpose of jQuery (just read the first paragraph: "What is jQuery?"). jQuery is a framework built on top of javascript to manipulate the DOM in the browser. For what you need you only need a simple javascript expression:
function trimToLen(str, maxLen) {
var trimmed = str.substr(0, maxLen);
return trimmed.substr(0, trimmed.lastIndexOf(' ')) + '…';
}
to make it work for strings shorter than the maxLex you have to add an additional condition:
function trimToLen(str, maxLen) {
if (str.length <= maxLen) {
return str;
}
var trimmed = str.substr(0, maxLen);
return trimmed.substr(0, trimmed.lastIndexOf(' ')) + '…';
}
and now the examples:
trimToLen("too short", 15);
// returns: too short
trimToLen("equal to maxLen", 15);
// returns: equal to maxLen
trimToLen("a little more than maxLen", 15);
// returns: a little more…
Notice that I used … (elipsis) instead of ... (3 x dot). Visually it is is pretty much the same but you save a couple of characters and also avoid complicating the logic with the length of the trimmed text (because you have 3 instead of 1 character).
Another thing you might want is to normalise spaces in order to catch tabs, new lines or spaces. This could be the case when you want to display a longer description (containing formatted text) in one short <a> or <span> tag. For that you can use a simple regex as the first expression in the function:
str = str.replace(/\s/g, ' ');

Just for completeness, you can do slightly better using the 2-arg form of lastIndexOf:
var ellipsis = "...";
function Truncate(text, maxLength)
{
if (text.length <= maxLength)
return text;
maxLength -= ellipsis.length;
var space = text.lastIndexOf(" ", maxLength);
if (space >= 0)
maxLength = space;
return text.slice(0, maxLength) + ellipsis;
}

Related

how to replace a char in string with many chars

I want to change a char in string with many values
I have string like this :
date_format = "%m/%d/%Y";
And i want to replace ever % with the char which after, so the date variable should be like this:
date_format="mm/dd/YY";
Here is what I tried so far, but i can't get it to work, so I need some help here:
function replaceon(str, index, chr) {
if (index > str.length - 1) return str;
return str.substr(0, index) + chr + str.substr(index + 1);
}
function locations(substring, string) {
var a = [],
i = -1;
while ((i = string.indexOf(substring, i + 1)) >= 0) a.push(i);
return a;
}
function corrent_format(date_format) {
var my_locations = locations('%', date_format);
console.log(my_locations.length);
for (var i = 0; i < my_locations.length; i++) {
replaceon(date_format, my_locations[i], date_format[my_locations[i] + 1]);
}
return date_format;
}
console.log(corrent_format(date_format));
You can try this:
"%m/%d/%Y".replace(/%([^%])/g,"$1$1")
Hope this hepls.
You can use a regular expression for that:
var date_format="%m/%d/%Y";
var res = date_format.replace(/%(.)/g, "$1$1");
console.log(res);
function act(str) {
var res = "";
for (var i = 0; i < (str.length - 1); i++) {
if (str[i] === "%")
res += str[i + 1];
else
res += str[i];
}
res += str[i];
return res;
}
var date_format = "%m/%d/%Y";
console.log(act(date_format));
Your code is not working because the date_format variable is not being modified by the corrent_format function. The replaceon function returns a new string. If you assign the result to date_format, you should get the expected result:
for (var i = 0; i < my_locations.length; i++) {
date_format = replaceon(date_format, my_locations[i], date_format[my_locations[i]+1])
}
Alternatively, you could perform the replacement using String.replace and a regular expression:
date_format.replace(/%(.)/g, '$1$1');
For the regex-challenged among us, here's a translation of /%(.)/g, '$1$1':
/ means that the next part is going to be regex.
% find a %.
. any single character, so %. would match %m, %d, and/or %Y.
(.) putting it in parens means to capture the value to use later on.
/g get all the matches in the source string (instead of just the first one).
?1 references the value we captured before in (.).
?1?1 repeat the captured value twice.
So, replace every %. with whatever's in the ., times two.
Now, this regex expression is the most concise and quickest way to do the job at hand. But maybe you can't use regular expressions. Maybe you have a dyslexic boss who has outlawed their use. (Dyslexia and regex are uneasy companions at best.) Maybe you haven't put in the 47 hours screaming at regular expressions that aren't doing what you want, that you're required to put in before you're allowed to use them. Or maybe you just hate regular expressions.
If any of these apply, you can also do this:
var x = '%m/%d/%y';
x = x.replace('%', 'm');
x = x.replace('%', 'd');
x = x.replace('%', 'y');
alert(x);
This takes advantage of the fact that the replace function only replaces the first match found.
But seriously, don't use this. Use regex. It's always better to invest that 20 hours working out a regex expression that condenses the 20 lines of code you wrote in 15 minutes down to one. Unless you have to get it done sometime tonight, and whatever you're trying just doesn't work, and it's getting close to midnight, and you're getting tired...well, no. Use regex. Really. Resist the temptation to avoid finding a regex solution. You'll be glad you did when you wake up at your desk in the morning, having missed your deadline, and get to go home and spend more time with your family, courtesy of your generous severance package.

How to remove string between two characters every time they occur [duplicate]

This question already has answers here:
Strip HTML from Text JavaScript
(44 answers)
removing html tags from string
(3 answers)
Closed 7 years ago.
I need to get rid of any text inside < and >, including the two delimiters themselves.
So for example, from string
<brev-y>th</brev-y><sw-ex>a</sw-ex><sl>t</sl>​
I would like to get this one
that
This is what i've tried so far:
var str = annotation.split(' ');
str.substring(str.lastIndexOf("<") + 1, str.lastIndexOf(">"))
But it doesn't work for every < and >.
I'd rather not use RegEx if possible, but I'm happy to hear if it's the only option.
You can simply use the replace method with /<[^>]*>/g.It matches < followed by [^>]* any amount of non> until > globally.
var str = '<brev-y>th</brev-y><sw-ex>a</sw-ex><sl>t</sl>';
str = str.replace(/<[^>]*>/g, "");
alert(str);
For string removal you can use RegExp, it is ok.
"<brev-y>th</brev-y><sw-ex>a</sw-ex><sl>t</sl>​".replace(/<\/?[^>]+>/g, "")
Since the text you want is always after a > character, you could split it at that point, and then the first character in each String of the array would be the character you need. For example:
String[] strings = stringName.split("<");
String word = "";
for(int i = 0; i < strings.length; i++) {
word += strings[i].charAt(0);
}
This is probably glitchy right now, but I think this would work. You don't need to actually remove the text between the "<>"- just get the character right after a '>'
Using a regular expression is not the only option, but it's a pretty good option.
You can easily parse the string to remove the tags, for example by using a state machine where the < and > characters turns on and off a state of ignoring characters. There are other methods of course, some shorter, some more efficient, but they will all be a few lines of code, while a regular expression solution is just a single replace.
Example:
function removeHtml1(str) {
return str.replace(/<[^>]*>/g, '');
}
function removeHtml2(str) {
var result = '';
var ignore = false;
for (var i = 0; i < str.length; i++) {
var c = str.charAt(i);
switch (c) {
case '<': ignore = true; break;
case '>': ignore = false; break;
default: if (!ignore) result += c;
}
}
return result;
}
var s = "<brev-y>th</brev-y><sw-ex>a</sw-ex><sl>t</sl>";
console.log(removeHtml1(s));
console.log(removeHtml2(s));
There are several ways to do this. Some are better than others. I haven't done one lately for these two specific characters, so I took a minute and wrote some code that may work. I will describe how it works. Create a function with a loop that copies an incoming string, character by character, to an outgoing string. Make the function a string type so it will return your modified string. Create the loop to scan from incoming from string[0] and while less than string.length(). Within the loop, add an if statement. When the if statement sees a "<" character in the incoming string it stops copying, but continues to look at every character in the incoming string until it sees the ">" character. When the ">" is found, it starts copying again. It's that simple.
The following code may need some refinement, but it should get you started on the method described above. It's not the fastest and not the most elegant but the basic idea is there. This did compile, and it ran correctly, here, with no errors. In my test program it produced the correct output. However, you may need to test it further in the context of your program.
string filter_on_brackets(string str1)
{
string str2 = "";
int copy_flag = 1;
for (size_t i = 0 ; i < str1.length();i++)
{
if(str1[i] == '<')
{
copy_flag = 0;
}
if(str1[i] == '>')
{
copy_flag = 2;
}
if(copy_flag == 1)
{
str2 += str1[i];
}
if(copy_flag == 2)
{
copy_flag = 1;
}
}
return str2;
}

Display only whole word using javascript

I have a text say "A sample text for testing". I need to display only ten characters in a div.
so i do substring on the text
txt.substring(0,10)
This gives me "A sample t". Since its ugly to display a unterminated word, i need only to display "A Sample" to be displayed. How do i do this?
You could do what you do, substringing the text to 10 chars.
Then you use txt.lastIndexOf(' ') to find the last space in the text.
Then you use that to substring the text again.
Example:
var txt = "A Sample Text";
txt = txt.subString(0,10); // "A Sample T"
txt = txt.subString(0, txt.lastIndexOf(' ')); // "A Sample"
Let me know if it helps!
Assuming that you'd rather have a cut off string than an empty string, if the word is longer than ten characters:
function shorten(txt)
{
// if it's short or a space appears after the first 10 characters, keep the substring (simple case)
if (txt.length <= 10 || txt[10] === ' ') return txt;
// get the index of the last space
var i = txt.substring(0, 11).lastIndexOf(' ');
// if a space is found, return the whole words at the start of the string;
// otherwise return just the first 10 characters
return txt.substring(0, i === -1 ? 11 : i);
}
use substring method to do this
i think you should add a filter to check whether the 11th character is space or not with the substring method. otherwise the last valid word too might removed. get "New sample text for testing" for example.
this is the code.
str = "A sample text for testing"
ch11_space = (str[10] == ' ') ? 0 : 1;
str = str.substring(0,10);
if (ch11_space) {
str = str.substring(0,str.lastIndexOf(' '));
}
function getShortenedString(str)
{
var maxLength = 10; // whatever the max string can be
var strLength = str.length;
var shortenedStr = str.substr(0, maxLength);
var shortenedStrLength = shortenedStr.length;
var lastSpace = str.lastIndexOf(" ");
if(shortenedStrLength != strLength)
{
// only need to do manipulation if we have a shortened name
var strDiff = strLength - shortenedStrLength;
var lastSpaceDiff = shortenedStrLength - lastSpace;
if(strDiff > lastSpaceDiff) // non-whole word after space
{
shortenedStr = str.substr(0, lastSpace);
}
}
return shortenedStr;
}

javascript/jquery shortening a string without cutting word off

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

Display only 10 characters of a long string?

How do I get a long text string (like a querystring) to display a maximum of 10 characters, using JQuery?
Sorry guys I'm a novice at JavaScript & JQuery :S
Any help would be greatly appreciated.
If I understand correctly you want to limit a string to 10 characters?
var str = 'Some very long string';
if(str.length > 10) str = str.substring(0,10);
Something like that?
Creating own answer, as nobody has considered that the split might not happened (shorter text). In that case we don't want to add '...' as suffix.
Ternary operator will sort that out:
var text = "blahalhahkanhklanlkanhlanlanhak";
var count = 35;
var result = text.slice(0, count) + (text.length > count ? "..." : "");
Can be closed to function:
function fn(text, count){
return text.slice(0, count) + (text.length > count ? "..." : "");
}
console.log(fn("aognaglkanglnagln", 10));
And expand to helpers class so You can even choose if You want the dots or not:
function fn(text, count, insertDots){
return text.slice(0, count) + (((text.length > count) && insertDots) ? "..." : "");
}
console.log(fn("aognaglkanglnagln", 10, true));
console.log(fn("aognaglkanglnagln", 10, false));
var example = "I am too long string";
var result;
// Slice is JS function
result = example.slice(0, 10)+'...'; //if you need dots after the string you can add
Result variable contains "I am too l..."
And here's a jQuery example:
HTML text field:
<input type="text" id="myTextfield" />
jQuery code to limit its size:
var elem = $("#myTextfield");
if(elem) elem.val(elem.val().substr(0,10));
As an example, you could use the jQuery code above to restrict the user from entering more than 10 characters while he's typing; the following code snippet does exactly this:
$(document).ready(function() {
var elem = $("#myTextfield");
if (elem) {
elem.keydown(function() {
if (elem.val().length > 10)
elem.val(elem.val().substr(0, 10));
});
}
});
Update:
The above code snippet was only used to show an example usage.
The following code snippet will handle you issue with the DIV element:
$(document).ready(function() {
var elem = $(".tasks-overflow");
if(elem){
if (elem.text().length > 10)
elem.text(elem.text().substr(0,10))
}
});
Please note that I'm using text instead of val in this case, since the val method doesn't seem to work with the DIV element.
('very long string'.slice(0,10))+'...'
// "very long ..."
html
<p id='longText'>Some very very very very very very very very very very very long string</p>
javascript (on doc ready)
var longText = $('#longText');
longText.text(longText.text().substr(0, 10));
If you have multiple words in the text, and want each to be limited to at most 10 chars, you could do:
var longText = $('#longText');
var text = longText.text();
var regex = /\w{11}\w*/, match;
while(match = regex.exec(text)) {
text = text.replace(match[0], match[0].substr(0, 10));
}
longText.text(text);
What you should also do when you truncate the string to ten characters is add the actual html ellipses entity: …, rather than three periods.
Although this won't limit the string to exactly 10 characters, why not let the browser do the work for you with CSS:
.no-overflow {
white-space: no-wrap;
text-overflow: ellipsis;
overflow: hidden;
}
and then for the table cell that contains the string add the above class and set the maximum permitted width. The result should end up looking better than anything done based on measuring the string length.
A = "a lennnnnnnnnnnnngthy string ";
word = A.substring(0, number_of_words_to_appear) + "...";
console.log(word)
This looks more to me like what you probably want.
$(document).ready(function(){
var stringWithShorterURLs = getReplacementString($(".tasks-overflow").text());
function getReplacementString(str){
return str.replace(/(https?\:\/\/[^\s]*)/gi,function(match){
return match.substring(0,10) + "..."
});
}});
you give it your html element in the first line and then it takes the whole text, replaces urls with 10 character long versions and returns it to you.
This seems a little strange to only have 3 of the url characters so I would recommend this if possible.
$(document).ready(function(){
var stringWithShorterURLs = getReplacementString($(".tasks-overflow p").text());
function getReplacementString(str){
return str.replace(/https?\:\/\/([^\s]*)/gi,function(match){
return match.substring(0,10) + "..."
});
}});
which would rip out the http:// or https:// and print up to 10 charaters of www.example.com
Try this :)
var mystring = "How do I get a long text string";
mystring = mystring.substring(0,10);
alert(mystring);
#jolly.exe
Nice example Jolly. I updated your version which limits the character length as opposed to the number of words. I also added setting the title to the real original innerHTML , so users can hover and see what is truncated.
HTML
<div id="stuff">a reallly really really long titleasdfasdfasdfasdfasdfasdfasdfadsf</div>
JS
function cutString(id){
var text = document.getElementById(id).innerHTML;
var charsToCutTo = 30;
if(text.length>charsToCutTo){
var strShort = "";
for(i = 0; i < charsToCutTo; i++){
strShort += text[i];
}
document.getElementById(id).title = "text";
document.getElementById(id).innerHTML = strShort + "...";
}
};
cutString('stuff');
const text = 'imathelongtextblablabla'
const showLess = false
{!showLess && `${text.substring(0, 10)}`}
{!showLess && "..."}
Show this "long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text "
to
long text long text long ...
function cutString(text){
var wordsToCut = 5;
var wordsArray = text.split(" ");
if(wordsArray.length>wordsToCut){
var strShort = "";
for(i = 0; i < wordsToCut; i++){
strShort += wordsArray[i] + " ";
}
return strShort+"...";
}else{
return text;
}
};

Categories

Resources