javascript/jquery shortening a string without cutting word off - javascript

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

Related

How to highlight text by using regex

I'm trying writing a script to help highlight when match with regex. Below is my example that what I do now.
var text = "SOMETHING ~WEIRDs~ AND Not WEIRD";
var regexp = /\b(WEIRD)\b/
var matches = text.match(regexp);
for (i = 0; i < matches.length; i++) {
var replace_all = RegExp(matches[i] + "(?![^<]*>|[^<>]*<\/)", "ig");
text = text.replace(eval(replace_all), "<span style='background- color:yellow'>" + matches[i] + "</span>");
}
console.log(text);
The output of the code above is
SOMETHING ~<span style='background- color:yellow'>WEIRD</span>s~ AND Not <span style='background- color:yellow'>WEIRD</span>
The output I want is
SOMETHING ~WEIRDs~ AND Not <span style='background- color:yellow'>WEIRD</span>
I would like to know is that anyway to write a regex contains regex and words provided? Or have any other method can solve this incorrect replace issue.
Your outer regex is fine. The issue is with the inner replace_all regex in the loop , as it replaces all instances of the found string, no matter its position in the original string.
Instead use the original Regex with replace() using the matches within the replacement string, like this:
var text = "SOMETHING ~WEIRDs~ AND Not WEIRD";
var regexp = /\b(WEIRD)\b/
var text = text.replace(regexp, '<span style="background-color: yellow">$1</span>');
console.log(text);
Also, as a general rule, never, ever use eval(). There is always a better solution or alternative.

Replace substring in all lines in textarea using javascript

Am trying to replace a particular string from all lines using javascript. Here is sample
www.youtube.com/watch?v=s8IJkexsjlI&index=37&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=PYOQLPW6ewQ&index=38&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=ejRmaOHs1rk&index=39&list=PLB03EA9545DD188C3
I want to replace the 11 characters after '=' how can I do it with a variable
like var= 'hello123456'
so output will be
www.youtube.com/watch?v=hello123456&index=37&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=hello123456&index=38&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=hello123456&index=39&list=PLB03EA9545DD188C3
Here is regex solution, see the snippet below
document.addEventListener("DOMContentLoaded", function(){
var link = "www.youtube.com/watch?v=s8IJkexsjlI&index=37&list=PLB03EA9545DD188C3";
var value = "hello123456";
link = link.replace(/\?v=(.*)\&index/g, "?v="+value+"&index")
document.getElementById("id").innerHTML = link
});
Input link:
<div>www.youtube.com/watch?v=s8IJkexsjlI&index=37&list=PLB03EA9545DD188C3</div>
<br>
<br>
Output link:
<div id="id"></div>
Please check the below code
var youstr="www.youtube.com/watch?v=s8IJkexsjlI&index=37&list=PLB03EA9545DD188C3";
var start=youstr.indexOf("=");
var end=start+11;
var replaceStr=youstr.slice(start,start+11);
youstr=youstr.replace(replaceStr,"ReplaceString");
This is pretty straightforward solution, without any fanciness so you could easy understand what's happening.
var originalStr = 'www.youtube.com/watch?v=s8IJkexsjlI&index=37&list=PLB03EA9545DD188C3';
var textToReplaceWith = 'hello123456';
var newStr = '';
// get index where unwanted text starts
var index = originalStr.indexOf('v=') + 2;
newStr = originalStr.substring(0, index); //take part just before the unnecessary text
newStr += textToReplaceWith; //add string you want
newStr += originalStr.substring(index + 11, originalStr.length) // take text part after unwanted text

Javascript string replace() method malfunctioning for dots and commas

I want to replace a text by using the user input values but for the below script dots and commas are malfunctioning when replacing. I tried (/\x/) method but it's not working, maybe because it's a value. So, how can I execute output more accurately?
function myFunction() {
var str = document.getElementById("text").value;
var x = new RegExp(document.getElementById("x").value, "g");
var y = document.getElementById("y").value;
var txt = str.replace(x, y);
document.getElementById("newText").innerHTML = txt;
}
function reset() {
document.getElementById("text").value = "";
}
example:
text = ..........a.a.a..a..a..aaaaaa..a.a.
x = ..a
y = B
output = ........B.BBBBBaaB.a.
but output should be
........B.a.aBBBaaaaaB.a.
(Sorry for the unprofessional example...)
I am just now learning JS and not a professional and I'm trying to make a replacer web page using JS like in MS Notepad where you can press ctrl+H and replace any word or letter.
You're looking for RegExp.escape, unlucky for you - the smart people at the JavaScript technical committee decided to postpone its inclusion in the standard because of an edge case you, or anyone else will likely never run into.
if(!RegExp.escape){
RegExp.escape = function(s){
return String(s).replace(/[\\^$*+?.()|[\]{}]/g, '\\$&');
};
}
Then, you can call it on a value and it'll escape it for use in new RegExp:
var raw = document.getElementById("x").value;
var x = new RegExp(RegExp.escape(raw), "g");
You want this regex - [.]{2}[a] or [.][.][a].
Two dots mandatory with trailing a. And it should be of 3 characters.

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

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