I have strings like this:
abcdefg
abcde
abc
jjjj
I need is them trucated to show like this if more than a specified lenght:
abc ..
abc ..
abc
jjj ..
Is there any simple javascript code I can use for this functionality
The length property will tell you how many characters you have, and the substr method will let you extract the first three (if there are more than you want), you can then concatenate " .." with the + operator (although "…" would be the usual choice).
function truncate(str, len) {
if(str.length > len) {
return str.substring(0, len) + ' ..';
} else {
return str;
}
}
Well, without knowing if you have access to Array.each and some of the more recent additions:
// if you have them all in an array, loop through the array/
for( var i = 0; i < strs.length; i++ )
// substr( ind, len ) = return a substring
// beginning at index ind and of len length
strs[ i ] = strs[ i ].substr( 0, 3 );
Now, if you don't have them all in an array, then things become a good deal harder. How are you currently storing them?
I think the substring function would be helpful. If you can get the length of a string, use substring to truncate and concatenate ".." as necessary, this is easy. You could make it a function and encapsulate everything. Would you like help with the code?
All string will have a length property you can use to check length, but I would just pull a substring:
var str = 'abcdefg';
var shortened = str.substr(0,3);
see http://www.electrictoolbox.com/javascript-substr/ for details
else a simple code will do
var mystring = "aaaaaaaaaa";
var max_length = 3; //max length
mystring = mystring.substr(0, max_length);
mystring = mystring + '..'
Related
I am trying to replace a string with two sets of patterns. For example,
var pattern1 = '12345abcde/'; -> this is dynamic.
var myString = '12345abcde/hd123/godaddy_item'
my end goal is to get the value between two slashes which is hd123
I have
var stringIneed = myString.replace(pattern1, '').replace('godaddy_item','');
The above codes work but I think there is more elegant solution. Can anyone help me out on this? Thanks a lot!
UPDATE:
To be more clear, the pattern is per environement string. For example,
pattern1 could be something like:
https://myproject-development/item on development environment.
and
https://myproject/item on Production
myString could usually be like
https://myproject/item/hd123/godaddy_item
or
https://myproject-development/item/hd123/godaddy_item
and I need to get 'hd123' in my case.
I'd strongly suggest not using regular expressions for this, especially when simple String and Array methods will easily suffice and be far more understandable, such as:
// your question shows you can anticipate the sections you
// don't require, so put both/all of those portions into an
// array:
var unwanted = ['12345abcde', 'godaddy_item'],
// the string you wish to find the segment from:
myString = '12345abcde/hd123/godaddy_item',
// splitting the String into an array by splitting on the '/'
// characters, filtering that array using an arrow function
// in which the section is the current array-element of the
// array over which we're iterating; and here we keep those
// sections which are not found in the unwanted Array (the index
// an element not found in an Array is returned as -1):
desired = myString.split('/').filter(section => unwanted.indexOf(section) === -1);
console.log(desired); // ["hd123"]
Avoiding Arrow functions, for browsers not supporting ES6 (and having removed the code comments):
var unwanted = ['12345abcde', 'godaddy_item'],
myString = '12345abcde/hd123/godaddy_item',
desired = myString.split('/').filter(function (section) {
return unwanted.indexOf(section) === -1;
});
console.log(desired); // ["hd123"]
Or:
// the string to start with and filter:
var myString = '12345abcde/hd123/godaddy_item',
// splitting the string by the '/' characters and keeping those whose
// index is greater than 0 (so 'not the first') and also less than the
// length of the array-1 (since JS arrays are zero-indexed while length
// is 1-based):
wanted = myString.split('/').filter((section, index, array) => index > 0 && index < array.length - 1);
console.log(wanted); // ["hd123"]
JS Fiddle demo
If, however, the requisite string to be found is always the penultimate portion of the supplied string, then we can use Array.prototype.filter() to return only that portion:
var myString = '12345abcde/hd123/godaddy_item',
wanted = myString.split('/').filter((section, index, array) => index === array.length - 2);
console.log(wanted); // ["hd123"]
JS Fiddle demo.
References:
Array.prototype.filter().
Arrow functions.
String.prototype.split().
You can use
.*\/([^\/]+)\/.*$
Regex Demo
JS Demo
var re = /.*\/([^\/]+)\/.*$/g;
var str = '12345abcde/hd123/godaddy_item';
while ((m = re.exec(str)) !== null) {
document.writeln("<pre>" + m[1] + "</br>" + "</pre>");
}
You can easily do something like this:
myString.split('/').slice(-2)[0]
This will return the item directly, in simple most way.
var myString = 'https://myproject/item/hd123/godaddy_item';
console.log(myString.split('/').slice(-2)[0]); // hd123
myString = 'https://myproject-development/item/hd123/godaddy_item';
console.log(myString.split('/').slice(-2)[0]); // hd123
Try using match() as shown below:
var re = /\/(.*)\//;
var str = '12345abcde/hd123/godaddy_item';
var result = str.match(re);
alert(result[1]);
To say that David's answer will "easily suffice and be far more understandable" is a matter of opinion - this regex option (which includes building up the expression from variables) really couldn't be much simpler:
var pathPrefix = '12345abcde/'; //dynamic
var pathToTest = '12345abcde/hd123/godaddy_item';
var pattern = new RegExp(pathPrefix + '(.*?)\/')
var match = pattern.exec(pathToTest);
var result = (match != null && match[1] != null ? '[' + match[1] + ']' : 'no match was found.'); //[hd123]
I have a string which I need to separate correctly:
self.view.frame.size.height = 44
I need to get only view, frame, size, and height. And I need to do it with a regular expression.
So far I've tried a lot of variants, none of them are even close to what I want to get. And my code now looks like this:
var testString = 'self.view.frame.size.height = 44'
var re = new RegExp('\\.(.*)\\.', "g")
var array = re.exec(testString);
console.log('Array length is ' + array.length)
for (var i = 0; i < array.length; i++) {
console.log('<' + array[i] + ">");
}
And it doesn't work at all:
Array length is 2
<.view.frame.size.>
<view.frame.size>
I'm new at Javascript, so maybe I want the impossible, let me know.
Thanks.
In Javascript, executing a regexp with the g modifier doesn't return all the matches at once. You have to execute it repeatedly on the same input string, and each one returns the next match.
You also need to change the regexp so it only returns one word at a time. .* is greedy, so it returns the longest possible match, so it was returning all the words between the first and last .. [^.]* will match a sequence of non-dot characters, so it will just return one word. You can't include the second . in the regexp, because that will interfere with the repetition -- each repetition starts searching after the end of the previous match, and there's no beginning . after the ending . of the word. Also, there's no . after height, so the last word won't match it.
EDIT: I've changed the regexp to use \w* instead of [^.]*, because it was grabbing the whole height = 44 string instead of just height.
var testString = 'self.view.frame.size.height = 44';
var re = /\.(\w*)/g;
var array = [];
var result;
while (result = re.exec(testString)) {
array.push(result[1]);
}
console.log('Array length is ' + array.length)
for (var i = 0; i < array.length; i++) {
console.log('<' + array[i] + ">");
}
If you're sure that your data will be always in the same format you can use this:
function parse (string) {
return string.split(" = ").shift().split(".").splice(1);
}
In your context, split is a MUCH better option:
var str = "self.view.frame.size.height = 44";
var bits1 = str.split(" ")[0];
var bits2 = bits1.split(".");
bits2.shift(); // get rid of the unwanted self
console.log(bits2);
What I want to do is take a string such as "this.those.that" and get a substring to or from the nth occurrence of a character. So, from the start of the string to the 2nd occurrence of . would return "this.those". Likewise, from the 2nd occurrence of . to the end of the string would return "that". Sorry if my question is foggy, it's not that easy to explain. Also, please do not suggest making extra variables, and the result will be in a string and not an array.
You could do it without arrays, but it would take more code and be less readable.
Generally, you only want to use as much code to get the job done, and this also increases readability. If you find this task is becoming a performance issue (benchmark it), then you can decide to start refactoring for performance.
var str = 'this.those.that',
delimiter = '.',
start = 1,
tokens = str.split(delimiter).slice(start),
result = tokens.join(delimiter); // those.that
console.log(result)
// To get the substring BEFORE the nth occurence
var tokens2 = str.split(delimiter).slice(0, start),
result2 = tokens2.join(delimiter); // this
console.log(result2)
jsFiddle.
Try this :
"qwe.fs.xczv.xcv.xcv.x".replace(/([^\.]*\.){3}/, '');
"xcv.xcv.x"
"qwe.fs.xczv.xcv.xcv.x".replace(/([^\.]*\.){**nth**}/, ''); - where is nth is the amount of occurrence to remove.
I'm perplexed as to why you want to do things purely with string functions, but I guess you could do something like the following:
//str - the string
//c - the character or string to search for
//n - which occurrence
//fromStart - if true, go from beginning to the occurrence; else go from the occurrence to the end of the string
var cut = function (str, c, n, fromStart) {
var strCopy = str.slice(); //make a copy of the string
var index;
while (n > 1) {
index = strCopy.indexOf(c)
strCopy = strCopy.substring(0, index)
n--;
}
if (fromStart) {
return str.substring(0, index);
} else {
return str.substring(index+1, str.length);
}
}
However, I'd strongly advocate for something like alex's much simpler code.
Just in case somebody needs both "this" and "those.that" in a way as alex described in his comment, here is a modified code:
var str = 'this.those.that',
delimiter = '.',
start = 1,
tokens = str.split(delimiter),
result = [tokens.slice(0, start), tokens.slice(start)].map(function(item) {
return item.join(delimiter);
}); // [ 'this', 'those.that' ]
document.body.innerHTML = result;
If you really want to stick to string methods, then:
// Return a substring of s upto but not including
// the nth occurence of c
function getNth(s, c, n) {
var idx;
var i = 0;
var newS = '';
do {
idx = s.indexOf(c);
newS += s.substring(0, idx);
s = s.substring(idx+1);
} while (++i < n && (newS += c))
return newS;
}
Struggling with a regex requirement. I need to split a string into an array wherever it finds a forward slash. But not if the forward slash is preceded by an escape.
Eg, if I have this string:
hello/world
I would like it to be split into an array like so:
arrayName[0] = hello
arrayName[1] = world
And if I have this string:
hello/wo\/rld
I would like it to be split into an array like so:
arrayName[0] = hello
arrayName[1] = wo/rld
Any ideas?
I wouldn't use split() for this job. It's much easier to match the path components themselves, rather than the delimiters. For example:
var subject = 'hello/wo\\/rld';
var regex = /(?:[^\/\\]+|\\.)+/g;
var matched = null;
while (matched = regex.exec(subject)) {
print(matched[0]);
}
output:
hello
wo\/rld
test it at ideone.com
The following is a little long-winded but will work, and avoids the problem with IE's broken split implementation by not using a regular expression.
function splitPath(str) {
var rawParts = str.split("/"), parts = [];
for (var i = 0, len = rawParts.length, part; i < len; ++i) {
part = "";
while (rawParts[i].slice(-1) == "\\") {
part += rawParts[i++].slice(0, -1) + "/";
}
parts.push(part + rawParts[i]);
}
return parts;
}
var str = "hello/world\\/foo/bar";
alert( splitPath(str).join(",") );
Here's a way adapted from the techniques in this blog post:
var str = "Testing/one\\/two\\/three";
var result = str.replace(/(\\)?\//g, function($0, $1){
return $1 ? '/' : '[****]';
}).split('[****]');
Live example
Given:
Testing/one\/two\/three
The result is:
[0]: Testing
[1]: one/two/three
That first uses the simple "fake" lookbehind to replace / with [****] and to replace \/ with /, then splits on the [****] value. (Obviously, replace [****] with anything that won't be in the string.)
/*
If you are getting your string from an ajax response or a data base query,
that is, the string has not been interpreted by javascript,
you can match character sequences that either have no slash or have escaped slashes.
If you are defining the string in a script, escape the escapes and strip them after the match.
*/
var s='hello/wor\\/ld';
s=s.match(/(([^\/]*(\\\/)+)([^\/]*)+|([^\/]+))/g) || [s];
alert(s.join('\n'))
s.join('\n').replace(/\\/g,'')
/* returned value: (String)
hello
wor/ld
*/
Here's an example at rubular.com
For short code, you can use reverse to simulate negative lookbehind
function reverse(s){
return s.split('').reverse().join('');
}
var parts = reverse(myString).split(/[/](?!\\(?:\\\\)*(?:[^\\]|$))/g).reverse();
for (var i = parts.length; --i >= 0;) { parts[i] = reverse(parts[i]); }
but to be efficient, it's probably better to split on /[/]/ and then walk the array and rejoin elements that have an escape at the end.
Something like this may take care of it for you.
var str = "/hello/wo\\/rld/";
var split = str.replace(/^\/|\\?\/|\/$/g, function(match) {
if (match.indexOf('\\') == -1) {
return '\x00';
}
return match;
}).split('\x00');
alert(split);
I want to delete the first character of a string, if the first character is a 0. The 0 can be there more than once.
Is there a simple function that checks the first character and deletes it if it is 0?
Right now, I'm trying it with the JS slice() function but it is very awkward.
You can remove the first character of a string using substring:
var s1 = "foobar";
var s2 = s1.substring(1);
alert(s2); // shows "oobar"
To remove all 0's at the start of the string:
var s = "0000test";
while(s.charAt(0) === '0')
{
s = s.substring(1);
}
Very readable code is to use .substring() with a start set to index of the second character (1) (first character has index 0). Second parameter of the .substring() method is actually optional, so you don't even need to call .length()...
TL;DR : Remove first character from the string:
str = str.substring(1);
...yes it is that simple...
Removing some particular character(s):
As #Shaded suggested, just loop this while first character of your string is the "unwanted" character...
var yourString = "0000test";
var unwantedCharacter = "0";
//there is really no need for === check, since we use String's charAt()
while( yourString.charAt(0) == unwantedCharacter ) yourString = yourString.substring(1);
//yourString now contains "test"
.slice() vs .substring() vs .substr()
EDIT: substr() is not standardized and should not be used for new JS codes, you may be inclined to use it because of the naming similarity with other languages, e.g. PHP, but even in PHP you should probably use mb_substr() to be safe in modern world :)
Quote from (and more on that in) What is the difference between String.slice and String.substring?
He also points out that if the parameters to slice are negative, they
reference the string from the end. Substring and substr doesn´t.
Use .charAt() and .slice().
Example: http://jsfiddle.net/kCpNQ/
var myString = "0String";
if( myString.charAt( 0 ) === '0' )
myString = myString.slice( 1 );
If there could be several 0 characters at the beginning, you can change the if() to a while().
Example: http://jsfiddle.net/kCpNQ/1/
var myString = "0000String";
while( myString.charAt( 0 ) === '0' )
myString = myString.slice( 1 );
The easiest way to strip all leading 0s is:
var s = "00test";
s = s.replace(/^0+/, "");
If just stripping a single leading 0 character, as the question implies, you could use
s = s.replace(/^0/, "");
You can do it with substring method:
let a = "My test string";
a = a.substring(1);
console.log(a); // y test string
Did you try the substring function?
string = string.indexOf(0) == '0' ? string.substring(1) : string;
Here's a reference - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/substring
And you can always do this for multiple 0s:
while(string.indexOf(0) == '0')
{
string = string.substring(1);
}
One simple solution is to use the Javascript slice() method, and pass 1 as a parameter
let str = "khattak01"
let resStr = str.slice(1)
console.log(resStr)
Result : hattak01
var s = "0test";
if(s.substr(0,1) == "0") {
s = s.substr(1);
}
For all 0s: http://jsfiddle.net/An4MY/
String.prototype.ltrim0 = function() {
return this.replace(/^[0]+/,"");
}
var s = "0000test".ltrim0();
const string = '0My string';
const result = string.substring(1);
console.log(result);
You can use the substring() javascript function.
//---- remove first and last char of str
str = str.substring(1,((keyw.length)-1));
//---- remove only first char
str = str.substring(1,(keyw.length));
//---- remove only last char
str = str.substring(0,(keyw.length));
try
s.replace(/^0/,'')
console.log("0string =>", "0string".replace(/^0/,'') );
console.log("00string =>", "00string".replace(/^0/,'') );
console.log("string00 =>", "string00".replace(/^0/,'') );
Here's one that doesn't assume the input is a string, uses substring, and comes with a couple of unit tests:
var cutOutZero = function(value) {
if (value.length && value.length > 0 && value[0] === '0') {
return value.substring(1);
}
return value;
};
http://jsfiddle.net/TRU66/1/
String.prototype.trimStartWhile = function(predicate) {
if (typeof predicate !== "function") {
return this;
}
let len = this.length;
if (len === 0) {
return this;
}
let s = this, i = 0;
while (i < len && predicate(s[i])) {
i++;
}
return s.substr(i)
}
let str = "0000000000ABC",
r = str.trimStartWhile(c => c === '0');
console.log(r);
Another alternative to get the first character after deleting it:
// Example string
let string = 'Example';
// Getting the first character and updtated string
[character, string] = [string[0], string.substr(1)];
console.log(character);
// 'E'
console.log(string);
// 'xample'
From the Javascript implementation of trim() > that removes and leading or ending spaces from strings. Here is an altered implementation of the answer for this question.
var str = "0000one two three0000"; //TEST
str = str.replace(/^\s+|\s+$/g,'0'); //ANSWER
Original implementation for this on JS
string.trim():
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,'');
}
}
Another alternative answer
str.replace(/^0+/, '')
var test = '0test';
test = test.replace(/0(.*)/, '$1');