I have a string, 15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt, I'd like to make it looks like 15.Prototypal...-Slider.txt
The length of the text is 56, how can I keep the first 12 letters and 10 last letters (incuding punctuation marks) and replace the others to ...
I don't really know how to commence the code, I made something like
var str="15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt";
str.split("// ",1);
although this gives me what I need, how do I have the results base on letters not words.
You can use str.slice().
function middleEllipsis(str, a, b) {
if (str.length > a + b)
return str.slice(0, a) + '...' + str.slice(-b);
else
return str;
}
middleEllipsis("15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt", 12, 10);
// "15.Prototypa...Slider.txt"
middleEllipsis("mpchc64.mov", 12, 10);
// "mpchc64.mov"
This function will do what you ask for:
function fixString(str) {
var LEN_PREFIX = 12;
var LEN_SUFFIX = 10;
if (str.length < LEN_PREFIX + LEN_SUFFIX) { return str; }
return str.substr(0, LEN_PREFIX) + '...' + str.substr(str.length - LEN_SUFFIX - 1);
}
You can adjust the LEN_PREFIX and LEN_SUFFIX as needed, but I've the values you specified in your post. You could also make the function more generic by making the prefix and suffix length input arguments to your function:
function fixString(str, prefixLength, suffixLength) {
if (str.length < prefixLength + suffixLength) { return str; }
return str.substr(0, prefixLength) + '...' + str.substr(str.length - suffixLength - 1);
}
I'd like to make it looks like 15.Prototypal...-Slider.txt
LIVE DEMO
No matter how long are the suffixed and prefixed texts, this will get the desired:
var str = "15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt",
sp = str.split('-'),
newStr = str;
if(sp.length>1) newStr = sp[0]+'...-'+ sp.pop() ;
alert( newStr ); //15.Prototypal...-Slider.txt
Splitting the string at - and using .pop() method to retrieve the last Array value from the splitted String.
Instead of splitting the string at some defined positions it'll also handle strings like:
11.jQuery-infinite-loop-a-Gallery.txt returning: 11.jQuery...-Gallery.txt
Here's another option. Note that this keeps the first 13 characters and last 11 because that's what you gave in your example.:
var shortenedStr = str.substr(0, 13) + '...' + str.substring(str.length - 11);
You could use the javascript substring command to find out what you want.
If you string is always 56 characters you could do something like this:
var str="15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt";
var newstr = str.substring(0,11) + "..." + str.substring(45,55)
if your string varies in length I would highly recommend finding the length of the string first, and then doing the substring.
have a look at: http://www.w3schools.com/jsref/jsref_substring.asp
Related
Im trying to replace a character at a specific indexOf to uppercase.
My string is a surname plus the first letter in the last name,
looking like this: "lovisa t".
I check the position with this and it gives me the right place in the string. So the second gives me 8(in this case).
first = texten.indexOf(" ");
second = texten.indexOf(" ", first + 1);
And with this I replace the first letter to uppercase.
var name = texten.substring(0, second);
name=name.replace(/^./, name[0].toUpperCase());
But how do I replace the character at "second" to uppercase?
I tested with
name=name.replace(/.$/, name[second].toUpperCase());
But it did´t work, so any input really appreciated, thanks.
Your error is the second letter isn't in position 8, but 7.
Also this second = texten.indexOf(" ", first + 1); gives -1, not 8, because you do not have a two spaces in your string.
If you know that the string is always in the format surname space oneLetter and you want to capitalize the first letter and the last letter you can simply do this:
var name = 'something s';
name = name[0].toUpperCase() + name.substring(1, name.length - 1) + name[name.length -1].toUpperCase();
console.log(name)
Here's a version that does exactly what your question title asks for: It uppercases a specific index in a string.
function upperCaseAt(str, i) {
return str.substr(0, i) + str.charAt(i).toUpperCase() + str.substr(i + 1);
}
var str = 'lovisa t';
var i = str.indexOf(' ');
console.log(upperCaseAt(str, i + 1));
However, if you want to look for specific patterns in the string, you don't need to deal with indices.
var str = 'lovisa t';
console.log(str.replace(/.$/, function (m0) { return m0.toUpperCase(); }));
This version uses a regex to find the last character in a string and a replacement function to uppercase the match.
var str = 'lovisa t';
console.log(str.replace(/ [a-z]/, function (m0) { return m0.toUpperCase(); }));
This version is similar but instead of looking for the last character, it looks for a space followed by a lowercase letter.
var str = 'lovisa t';
console.log(str.replace(/(?:^|\s)\S/g, function (m0) { return m0.toUpperCase(); }));
Finally, here we're looking for (and uppercasing) all non-space characters that are preceded by the beginning of the string or a space character; i.e. we're uppercasing the start of each (space-separated) word.
All can be done by regex replace.
"lovisa t".replace(/(^|\s)\w/g, s=>s.toUpperCase());
Try this one (if it will be helpfull, better move constants to other place, due performance issues(yes, regexp creation is not fast)):
function normalize(str){
var LOW_DASH = /\_/g;
var NORMAL_TEXT_REGEXP = /([a-z])([A-Z])/g;
if(!str)str = '';
if(str.indexOf('_') > -1) {
str = str.replace(LOW_DASH, ' ');
}
if(str.match(NORMAL_TEXT_REGEXP)) {
str = str.replace(NORMAL_TEXT_REGEXP, '$1 $2');
}
if(str.indexOf(' ') > -1) {
var p = str.split(' ');
var out = '';
for (var i = 0; i < p.length; i++) {
if (!p[i])continue;
out += p[i].charAt(0).toUpperCase() + p[i].substring(1) + (i !== p.length - 1 ? ' ' : '');
}
return out;
} else {
return str.charAt(0).toUpperCase() + str.substring(1);
}
}
console.log(normalize('firstLast'));//First Last
console.log(normalize('first last'));//First Last
console.log(normalize('first_last'));//First Last
I have an input field that expects a 10 digit number. If the user enters and submits a number less than 10 digits, the function would simply add a "0" until the inputed value is 10 digits in length.
I haven't really used, or understand how recursive functions really work, but I'm basically looking at an efficient way of doing this. One minor issue I'm having is figuring out how to prepend the "0"s at the beginning of the string rather than appended to the end.
My thinking:
function lengthCheck(sQuery) {
for (var i = 0; i < sQuery.length; i++) {
if (sQuery.length !== 10) {
sQuery += "0";
//I'd like to add the 0s to the beggining of the sQuery string.
console.log(sQuery);
lengthCheck(sQuery);
} else return sQuery
}
}
Change:
sQuery += "0"; // added at end of string
to:
sQuery = "0" + sQuery; // added at start of string
To remove the for loop/recursion, you could slice out the desired length in one step:
function padZeros(sQuery) {
// the max amount of zeros you want to lead with
const maxLengthZeros = "0000000000";
// takes the 10 rightmost characters and outputs them in a new string
return (maxLengthZeros + sQuery).slice(-10);
}
Simple generic function using ES6 repeat:
// edge case constraints not implemented for brevity
function padZeros(sQuery = "", maxPadding = 10, outputLength = 10) {
// the max amount of zeros you want to lead with
const maxLengthZeros = "0".repeat(maxPadding);
// returns the "outputLength" rightmost characters
return (maxLengthZeros + sQuery).slice(-outputLength);
}
console.log('padZeros: ' + padZeros("1234567890"));
console.log('padZeros: ' + padZeros("123"));
console.log('padZeros: ' + padZeros(""));
Alternate version that doesn't affect strings over your set limit:
function padZerosIfShort(inputString = "", paddedOutputLength = 10) {
let inputLen = inputString.length;
// only padded if under set length, otherwise returned untouched
return (paddedOutputLength > inputLen)
? "0".repeat(paddedOutputLength - inputLen) + inputString
: inputString;
}
console.log('padZerosIfShort: ' + padZerosIfShort("1234567890", 5));
console.log('padZerosIfShort: ' + padZerosIfShort("123", 5));
console.log('padZerosIfShort: ' + padZerosIfShort("", 5));
It will ultimately depend on your needs how you want to implement this behavior.
The += operator adds things to the end of strings similar to:
sQuery=sQuery+"0"
You can add characters to the front of a string like this
sQuery="0"+sQuery
I also found something interesting here. it works like this:
("00000" + sQuery).slice(-5)
You would add zeros to the front then slice off everything except the last 5. so to get 10 characters you would use:
("0000000000" + n).slice(-10)
You don't need recursion to solve this, just a simple for loop should do the trick. Try this:
function lengthCheck (sQuery) {
for (var i = sQuery.length; i<10; i++) {
sQuery = "0" + sQuery;
}
return sQuery;
}
You're looking to pad the string with zeroes. This is an example I've used before from here and will shorten your code a little bit:
function lengthCheck (sQuery) {
while (sQuery.length < 10)
sQuery = 0 + sQuery;
return sQuery;
}
I believe this has already been answered here (or similar enough to provide you the solution): How to output integers with leading zeros in JavaScript
I have a string, var str = "Runner, The (1999)";
Using substr(), I need to see if ", The" is contained in str starting from 7 characters back, then if it is, remove those characters and put them in the start. Something like this:
if (str.substr(-7) === ', The') // If str has ', The' starting from 7 characters back...
{
str = 'The ' + str.substr(-7, 5); // Add 'The ' to the start of str and remove it from middle.
}
The resulting str should equal "The Runner (1999)"
Please, no regular expressions or other functions. I'm trying to learn how to use substr.
Here you go, using only substr as requested:
var str = "Runner, The (1999)";
if(str.substr(-12, 5) === ', The') {
str = 'The ' + str.substr(0, str.length - 12) + str.substr(-7);
}
alert(str);
Working JSFiddle
It should be noted that this is not the best way to achieve what you want (especially using hardcoded values like -7 – almost never as good as using things like lastIndexOf, regex, etc). But you wanted substr, so there it is.
var str = "Runner, The (1999)";
if(str.indexOf(", The") != -1) {
str = "The "+str.replace(", The","");
}
If you want to use just substr:
var a = "Runner, The (1999)"
var newStr;
if (str.substr(-7) === ', The')
newStr= 'The ' +a.substr(0,a.length-a.indexOf('The')-4) + a.substr(a.indexOf('The')+3)
Use a.substr(0,a.length-a.indexOf('The')-4) to obtain the words before "The" and a.substr(a.indexOf('The')+3) to obtain the words after it.
So, you say that the solution should be limited to only substr method.
There will be different solutions depending on what you mean by:
", The" is contained in str starting from 7 characters back
If you mean that it's found exactly in -7 position, then the code could look like this (I replaced -7 with -12, so that the code returned true):
function one() {
var a = "Runner, The (1999)";
var b = ", The";
var c = a.substr(-12, b.length);
if (c == b) {
a = "The " + a.substr(0, a.length - 12) +
a.substr(a.length - 12 + b.length);
}
}
If, however, substring ", The" can be found anywhere between position -7 and the end of the string, and you really need to use only substr, then check this out:
function two() {
var a = "Runner, The (1999)";
var b = ", The";
for (var i = a.length - 12; i < a.length - b.length; i++) {
if (a.substr(i, b.length) == b) {
a = "The " + a.substr(0, i) + a.substr(i + b.length);
break;
}
}
}
I have a function that get string, I'm looking for a way to format the 3rd word (which is number, that i want to format it with comma). any idea how to do it?
should be something like that:
function formatNumber(txt){
return txt.replace(3rd-word, formatNumber(3rd-word));
}
Match any word that consists of digits, and format it:
txt = txt.replace(/\b(\d+)\b/g, format);
using a formatting function, for example:
function format(s) {
var r = '';
while (s.length > 3) {
r = ',' + s.substr(s.length - 3) + r;
s = s.substr(0, s.length - 3);
}
return s + r;
}
Demo: http://jsfiddle.net/Guffa/5yA62/
Break it down into parts.
Create a function that transforms your word into the format you want.
Split your sentence into words.
Run that function against the appropriate word.
Put the words back into a sentence.
This does not solve your problem. You would still need to find a way to format the number as you choose, but it solves a similar problem of uppercasing the third word:
var transformNth = function(n, fn) {
return function(arr) {
arr[n] = fn(arr[n]);
return arr;
}
};
var makeWords = function(sentence) {return sentence.split(" ");};
var upperCase = function(word) {return word.toUpperCase();}
var transformSentence = function(sentence) {
// index 2 is the third word
return transformNth(2, upperCase)(makeWords(sentence)).join(" ");
}
transformSentence("I have a function that get string");
//=> "I have A function that get string"
transformSentence("I'm looking for a way to format the 3rd word");
//=> "I'm looking FOR a way to format the 3rd word"
transformSentence("which is number");
//=> "which is NUMBER"
transformSentence("that i want to format it with comma");
//=> "that i WANT to format it with comma"
transformSentence("any idea how to do it?");
//=> "any idea HOW to do it?"
transformSentence("should be something like that");
//=> "should be SOMETHING like that"
It might have problems if your sentences have some more complicated structure than single whitespace separation of words that you want to maintain...
You can get the n-th word from the sentence by splitting it up and executing a replace on the word index as specified.
Here is a demo for the code below: DEMO
var sentence = "Total is 123456789!"
var formatNumber = function(value) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
var replaceWord = function(sentence, pos, formatterFunction) {
var matches = sentence.match(/(\b[^\s]+\b)/g);
if (pos < 0 && pos >= matches.length) {
throw "Index out of bounds: " + pos;
}
var match = matches[pos];
var bounded = new RegExp('\\b' + match + '\\b');
return sentence.replace(bounded, formatterFunction(match));
};
console.log(replaceWord(sentence, 2, formatNumber)); // Total is 123,456,789!
How can I, using Javascript, make a function that will trim string passed as argument, to a specified length, also passed as argument. For example:
var string = "this is a string";
var length = 6;
var trimmedString = trimFunction(length, string);
// trimmedString should be:
// "this is"
Anyone got ideas? I've heard something about using substring, but didn't quite understand.
Why not just use substring... string.substring(0, 7); The first argument (0) is the starting point. The second argument (7) is the ending point (exclusive). More info here.
var string = "this is a string";
var length = 7;
var trimmedString = string.substring(0, length);
Copying Will's comment into an answer, because I found it useful:
var string = "this is a string";
var length = 20;
var trimmedString = string.length > length ?
string.substring(0, length - 3) + "..." :
string;
Thanks Will.
And a jsfiddle for anyone who cares https://jsfiddle.net/t354gw7e/ :)
I suggest to use an extension for code neatness.
Note that extending an internal object prototype could potentially mess with libraries that depend on them.
String.prototype.trimEllip = function (length) {
return this.length > length ? this.substring(0, length) + "..." : this;
}
And use it like:
var stringObject= 'this is a verrrryyyyyyyyyyyyyyyyyyyyyyyyyyyyylllooooooooooooonggggggggggggsssssssssssssttttttttttrrrrrrrrriiiiiiiiiiinnnnnnnnnnnnggggggggg';
stringObject.trimEllip(25)
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substr
From link:
string.substr(start[, length])
let trimString = function (string, length) {
return string.length > length ?
string.substring(0, length) + '...' :
string;
};
Use Case,
let string = 'How to trim a string to N chars in Javascript';
trimString(string, 20);
//How to trim a string...
Prefer String.prototype.slice over the String.prototype.substring method (in substring, for some cases it gives a different result than what you expect).
Trim the string from LEFT to RIGHT:
const str = "123456789";
result = str.slice(0,5); // "12345", extracts first 5 characters
result = str.substring(0,5); // "12345"
startIndex > endIndex:
result = str.slice(5,0); // "", empty string
result = str.substring(5,0); // "12345" , swaps start & end indexes => str.substring(0,5)
Trim the string from RIGHT to LEFT: (-ve start index)
result = str.slice(-3); // "789", extracts last 3 characters
result = str.substring(-3); // "123456789" , -ve becomes 0 => str.substring(0)
result = str.substring(str.length - 3); // "789"
Little late... I had to respond. This is the simplest way.
// JavaScript
function fixedSize_JS(value, size) {
return value.padEnd(size).substring(0, size);
}
// JavaScript (Alt)
var fixedSize_JSAlt = function(value, size) {
return value.padEnd(size).substring(0, size);
}
// Prototype (preferred)
String.prototype.fixedSize = function(size) {
return this.padEnd(size).substring(0, size);
}
// Overloaded Prototype
function fixedSize(value, size) {
return value.fixedSize(size);
}
// usage
console.log('Old school JS -> "' + fixedSize_JS('test (30 characters)', 30) + '"');
console.log('Semi-Old school JS -> "' + fixedSize_JSAlt('test (10 characters)', 10) + '"');
console.log('Prototypes (Preferred) -> "' + 'test (25 characters)'.fixedSize(25) + '"');
console.log('Overloaded Prototype (Legacy support) -> "' + fixedSize('test (15 characters)', 15) + '"');
Step by step.
.padEnd - Guarentees the length of the string
"The padEnd() method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end (right) of the current string. The source for this interactive example is stored in a GitHub repository."
source: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
.substring - limits to the length you need
If you choose to add ellipses, append them to the output.
I gave 4 examples of common JavaScript usages. I highly recommend using the String prototype with Overloading for legacy support. It makes it much easier to implement and change later.
Just another suggestion, removing any trailing white-space
limitStrLength = (text, max_length) => {
if(text.length > max_length - 3){
return text.substring(0, max_length).trimEnd() + "..."
}
else{
return text
}
There are several ways to do achieve this
let description = "your test description your test description your test description";
let finalDesc = shortMe(description, length);
function finalDesc(str, length){
// return str.slice(0,length);
// return str.substr(0, length);
// return str.substring(0, length);
}
You can also modify this function to get in between strings as well.
Here is my solution, which includes trimming white space too.
const trimToN = (text, maxLength, dotCount) => {
let modText = text.trim();
if (modText.length > maxLength) {
modText = text.substring(0, maxLength - dotCount);
modText = modText.padEnd(maxLength, ".");
return modText;
}
return text;
};
trimToN('Javascript', 6, 2) will return "Java.."
I think that you should use this code :-)
// sample string
const param= "Hi you know anybody like pizaa";
// You can change limit parameter(up to you)
const checkTitle = (str, limit = 17) => {
var newTitle = [];
if (param.length >= limit) {
param.split(" ").reduce((acc, cur) => {
if (acc + cur.length <= limit) {
newTitle.push(cur);
}
return acc + cur.length;
}, 0);
return `${newTitle.join(" ")} ...`;
}
return param;
};
console.log(checkTitle(str));
// result : Hi you know anybody ...