I need to remove all characters of a string after 5th character,
for example
my string is
P-CI-7-C-71
and the output should be like
P-CI-
Use substring
alert("P-CI-7-C-71".substring(0, 5));
So you can use it like
var str='P-CI-7-C-71'.substring(0, 5);
You can also use substr, that will work the same in this case but remember they work differently so they are not generally interchangeable
var str='P-CI-7-C-71'.substr(0, 5);
Difference can be noticed in the prototype
str.substring(indexStart[, indexEnd])
VS
str.substr(start[, length])
Extracting String Parts
There are 3 methods for extracting a part of a string:
slice(start, end)
substring(start, end)
substr(start, length)
With String#substring:
The substring() method returns a subset of a string between one index and another, or through the end of the string.
document.write('P-CI-7-C-71'.substring(0, 5));
Try this:
alert('P-CI-7-C-71'.substring(0,5));
var str = 'P-CI-7-C-71';
var res = str.slice(0,5);
alert(res);
Use Can use substring function in the JS
the Substring(StringName,StartPosition, End Position);
Related
How to use the javascript split splice slice methods to convert the:
1.18.0-AAA-1 into 1.18.0.
Start with the initial value, determine that the portion you want is before the first hyphen, so use that as the delimiter for the split. Perform the split and then the first portion will be everything up to but not including that first hyphen. You don't need slice or splice for this - just split. Then just add the dot at the end for the trailing dot.
var x="1.18.0-AAA-1";
var y=x.split("-");//splits it at each "-";
var z=y[0]+".";//gives 1.18.0.
however if you are asking to use each of the threeemethods to yield the outcome, then this sounds like homework and you should try doing it on your own. Best way to learn is to try.
Use split to create an array from your string
var str = "1.18.0-AAA-1";
var parts = str.split("-"); // this returns the array ["1.18.0", "AAA", "1"]
Now the easiest way to get what you want is doing:
parts[0];
I am doing some JavaScript coding and have to process a string to a array.
The original string is this: "red,yellow,blue,green,grey"
What I want to get is an array like this: ["red","yellow","blue","green","grey"]
I have tried to write a function to do this, use indexOf() to get the position of commas then do some further processing. But I think it's to heavy this way. Is there a better way to use regular expression or some existed JavaScript method to implement my purpose?
Thanks all.
use string.split function to split the original string by comma.......
string.split(",")
You can use split:
The split() method splits a String object into an array of strings by separating the string into substrings.
var arr = "red,yellow,blue,green,grey".split(',');
OR
You can also use regex:
var arr = "red,yellow,blue,green,grey".match(/\w+/g);
Try the string.split() method. For further details refer to:
http://www.w3schools.com/jsref/jsref_split.asp
var str = "red,yellow,blue,green,grey";
var res = str.split(",");
you can use .split() function.
Example
.split() : Split a string into an array of substrings:
var str = "red,yellow,blue,green,grey";
var res = str.split(",");
alert(res);
You can use following regular expression ..
[^,]*
How I can get the value after last char(. ; + _ etc.):
e.g.
string.name+org.com
I want to get "com".
Is there any function in jQuery?
Use lastIndexOf and substr to find the character and get the part of the string after it:
var extension = name.substr(name.lastIndexOf(".") + 1);
Demo: http://jsfiddle.net/Guffa/K3BWn/
A simple and readable approch to get the substring after the last occurrence of a character from a defined set is to split the string with a regular expression containing a character class and then use pop() to get the last element of the resulting array:
The pop() method removes the last element from an array and returns that element.
See a JS demo below:
var s = 'string.name+org.com';
var result = s.split(/[.;+_]/).pop();
console.log(result);
to split at all non-overlapping occurrences of the regex by default.
NOTE: If you need to match ^, ], \ or -, you may escape them and use anywhere inside the character class (e.g. /[\^\-\]\\]/). It is possible to avoid escaping ^ (if you do not put it right after the opening [), - (if it is right after the opening [, right before the closing ], after a valid range, or between a shorthand character class and another symbol): /[-^\]\\]/.
Also, if you need to split with a single char, no regex is necessary:
// Get the substring after the last dot
var result = 'string.name+org.com'.split('.').pop();
console.log(result);
Not jQuery, just JavaScript: lastIndexOf and substring would do it (not since the update indicating multiple characters). As would a regular expression with a capture group containing a character class followed by an end-of-string anchor, e.g. /([^.;+_]+)$/ used with RegExp#exec or String#match.
E.g. (live copy | source):
var match = /([^.;+_]+)$/.exec(theStringToTest),
result = match && match[1];
var s = "string.name+org.com",
lw = s.replace(/^.+[\W]/, '');
console.log(lw) /* com */
this will also work for
string.name+org/com
string.name+org.info
You can use RegExp Object.
Try this code:
"http://stackoverflow.com".replace(/.*\./,"");
I'll throw in a crazy (i.e. no RegExp) one:
var s = 'string.name+org.com';
var a = s.split('.'); //puts all sub-Strings delimited by . into an Array
var result = a[a.length-1]; //gets the last element of that Array
alert(result);
EDIT: Since the update of the question is demanding mutiple delimiters to work this is probably not the way to go. Too crazy.....
use javascript function like
url.substr(url.length - 3);
maybe this is too late to consider, this codes works fine for me using jquery
var afterDot = value.substr(value.lastIndexOf('_') + 1);
You could just replate '_' to '.'
var myString = 'asd/f/df/xc/asd/test.jpg'
var parts = myString.split('/');
var answer = parts[parts.length - 1];
console.log(answer);
I have two strings such as:
sometext~somemoretext~extratext
and
sometext~otherextratext
I wish to crop off the last tilde (~) and all text to the right. For instance, the above two strings would result in:
sometext~somemoretext
and
sometext
Thanks
lastIndexOf(char) returns the position of the last found occurrence of a specified value in a string
substring(from, to) extracts the characters from a string, between two specified indices, and returns the new sub string
For instance:
var txt = 'sometext~somemoretext~extratext';
txt = txt.substring(0, txt.lastIndexOf('~'));
DEMO
I strongly suggest you to read the doc on the Javascript String Object
return theString.replace(/~[^~]*$/, '');
You can do this using a regular expression with the .replace() DOCs method.
var str = 'sometext~somemoretext~extratext';
str = str.replace(/~[\w\s]+$/, '');
Here is a jsFiddle of the above code for you to run: http://jsfiddle.net/NELFB/
you can use substr to split the string, then rebuild them for what ever you need
var someString = "sometext~otherextratext";
someString = someString.split('~');
this will give you an array, which you can use like someString[0];
use .replace('~', '') if you need to further remove the ones at the end of strings
this should do it
function removeExtra(input){
return input.substr(0,input.lastIndexOf('~'))
}
I have a value "319CDXB" everytime i have to access last three characters of the Strring how can i do this . Usually the Length varies all the time .Everytime I need the last characters of the String using Jquery
The String .slice() method lets you use a negative index:
var str = "319CDXB".slice( -3 ); // DXB
EDIT: To expound a bit, the .slice() method for String is a method that behaves very much like its Array counterpart.
The first parameter represents the starting index, while the second is the index representing the stopping point.
Either parameter allows a negative index to be employed, as long as the range makes sense. Omitting the second parameter implies the end of the String.
Example: http://jsfiddle.net/patrick_dw/N4Z93/
var str = "abcdefg";
str.slice(0); // "abcdefg"
str.slice(2); // "cdefg"
str.slice(2,-2); // "cde"
str.slice(-2); // "fg"
str.slice(-5,-2); // "cde"
The other nice thing about .slice() is that it is widely supported in all major browsers. These two reasons make it (in my opinion) the most appealing option for obtaining a section of a String.
You can do this with regular JavaScript:
var str = "319CDXB";
var lastThree = str.substr(str.length - 3);
If you're getting it from jQuery via .val(), just use that as your str in the above code.
Simple:
str = "319CDXB"
last_three = str.substr(-3)
var str = "319CDXB";
str.substr(str.length - 3); // "DXB"