I have a string from which I am trying to get a specif value. The value is buried in the middle of the string. For example, the string looks like this:
Content1Save
The value I want to extract is "1";
Currently, I use the built-in substring function to get to remove the left part of the string, like this:
MyString = "Content1Save";
Position = MyString;
Position = Position.substring(7);
alert(Position); // alerts "1Save"
I need to get rid of the "Save" part and be left with the 1;
How do I do that?
+++++++++++++++++++++++++++++++++++++++++
ANSWER
Position = Position.substr(7, 1);
QUESTION
What's the difference between these two?
Position = Position.substr(7, 1);
Position = Position.substring(7, 1);
You can use the substr[MDN] method. The following example gets the 1 character long substring starting at index 7.
Position = Position.substr(7, 1);
Or, you can use a regex.
Position = /\d+/.exec(Position)[0];
I would suggest looking into regex, and groups.
Regex is built essentially exactly for this purpose and is built in to javascript.
Regex for something like Content1Save would look like this:
rg = /^[A-Za-z]*([0-9]+)[A-Za-z]*$/
Then you can extract the group using:
match = rg.exec('Content1Save');
alert(match[1]);
More on regex can be found here: http://en.wikipedia.org/wiki/Regular_expression
It highly depends on the rules you have for that middle part. If it's just a character, you can use Position = Position.substring(0, 1). If you're trying to get the number, as long as you have removed the letters before it, you can use parseInt.
alert(parseInt("123abc")); //123
alert(parseInt("foo123bar")); //NaN
If you're actually trying to search, you'll more often than not need to use something called Regular Expressions. They're the best search syntax JavaScript avails.
var matches = Position.match(/\d+/)
alert(matches[0])
Otherwise you can use a series of substr's, but that implies you know what is in the string to begin with:
MyString.substr(MyString.indexOf(1), 1);
But that is a tad annoying.
Related
How to make a format number like below in javascript, i try workit with some regex, but it's not working.
99.999.999.9.999.999
You could use a regular expression with positive lookahead for a special length to the end of the string.
var regex = /(?=(.{13}|.{10}|.{7}|.{6}|.{3})$)/g,
value = '999999999999999',
result = value.replace(regex, '.');
console.log(result);
(9999999999999).toString().split("").reverse().map((el,i)=>(i+1)%3==0?"."+el:el).reverse().join("");
Make a string array out of it, then start from behind and add a point after each third element, then create a String out of that.
http://jsbin.com/lepecoyedo/edit?console
Alternatively, with fixed , positions:
var num=(9999999999999).toString().split("").reverse();
[3,6,7].forEach((i,o)=>num.splice(o+i,0,"."));//positions 3,6,8 (or others) from behind
num=num.reverse().join("");
http://jsbin.com/xahopuhira/edit?console
I have the following example url: #/reports/12/expense/11.
I need to get the id just after the reports -> 12. What I am asking here is the most suitable way to do this. I can search for reports in the url and get the content just after that ... but what if in some moment I decide to change the url, I will have to change my algorythm.
What do You think is the best way here. Some code examples will be also very helpfull.
It's hard to write code that is future-proof since it's hard to predict the crazy things we might do in the future!
However, if we assume that the id will always be the string of consecutive digits in the URL then you could simply look for that:
function getReportId(url) {
var match = url.match(/\d+/);
return (match) ? Number(match[0]) : null;
}
getReportId('#/reports/12/expense/11'); // => 12
getReportId('/some/new/url/report/12'); // => 12
You should use a regular expression to find the number inside the string. Passing the regular expression to the string's .match() method will return an array containing the matches based on the regular expression. In this case, the item of the returned array that you're interested in will be at the index of 1, assuming that the number will always be after reports/:
var text = "#/reports/12/expense/11";
var id = text.match(/reports\/(\d+)/);
alert(id[1]);
\d+ here means that you're looking for at least one number followed by zero to an infinite amount of numbers.
var text = "#/reports/12/expense/11";
var id = text.match("#/[a-zA-Z]*/([0-9]*)/[a-zA-Z]*/")
console.log(id[1])
Regex explanation:
#/ matches the characters #/ literally
[a-zA-Z]* - matches a word
/ matches the character / literally
1st Capturing group - ([0-9]*) - this matches a number.
[a-zA-Z]* - matches a word
/ matches the character / literally
Regular expressions can be tricky (add expensive). So usually if you can efficiently do the same thing without them you should. Looking at your URL format you would probably want to put at least a few constraints on it otherwise the problem will be very complex. For instance, you probably want to assume the value will always appear directly after the key so in your sample report=12 and expense=11, but report and expense could be switched (ex. expense/11/report/12) and you would get the same result.
I would just use string split:
var parts = url.split("/");
for(var i = 0; i < parts.length; i++) {
if(parts[i] === "report"){
this.reportValue = parts[i+1];
i+=2;
}
if(parts[i] === "expense"){
this.expenseValue = parts[i+1];
i+=2;
}
}
So this way your key/value parts can appear anywhere in the array
Note: you will also want to check that i+1 is in the range of the parts array. But that would just make this sample code ugly and it is pretty easy to add in. Depending on what values you are expecting (or not expecting) you might also want to check that values are numbers using isNaN
There is a part in my string from, to which I would like to replace to an another string replace_string. My code should work, but what if there is an another part like the returned substring?
var from=10, to=17;
//...
str = str.replace(str.substring(from, to), replace_string);
For example:
from=4,to=6
str = "abceabxy"
replace_string = "zz"
the str should be "abcezzxy"
What you want to do is simple! Cut out and replace the string. Here is the basic tool, you need scissor and glue! Oops I mean string.Split() and string.Replace().
How to use?
Well I am not sure if you want to use string.Split() but you have used string.Replace() so here goes.
String.Replace uses two parameters, like this ("one", "two") what you need to make sure is that you are not replacing a char with a string or a string with a char. They are used as:
var str="Visit Microsoft!";
var n=str.replace("Microsoft","W3Schools");
Your code:
var from=10, to=17;
//...
var stringGot = str.replace(str.substring(from, to), replace_string);
What you should do will be to split the code first, and then replace the second a letter! As you want one in your example. Thats one way!
First, split the string! And then replaced the second a letter with z.
For String.Replace refer this: http://www.w3schools.com/jsref/jsref_replace.asp
For String.SubString: http://www.w3schools.com/jsref/jsref_substring.asp
For String.Split: http://www.w3schools.com/jsref/jsref_split.asp
Strings are immutable. This means they do not change after they are first instantiated. Every method to manipulate a string actually returns a new instance of a string. So you have to assign your result back to the variable like this:
str = str.replace(str.substring(from, to), replace_string);
Update: However, the more efficient way of doing this in the first place would be the following. it is also less prone to errors:
str = str.substring(0, from) + replace_string + str.substring(to);
See this fiddle: http://jsfiddle.net/cFtKL/
It runs both of the commands through a loop 100,000 times. The first takes about 75ms whereas the latter takes 20ms.
I have several Javascript strings (using jQuery). All of them follow the same pattern, starting with 'ajax-', and ending with a name. For instance 'ajax-first', 'ajax-last', 'ajax-email', etc.
How can I make a regex to only grab the string after 'ajax-'?
So instead of 'ajax-email', I want just 'email'.
You don't need RegEx for this. If your prefix is always "ajax-" then you just can do this:
var name = string.substring(5);
Given a comment you made on another user's post, try the following:
var $li = jQuery(this).parents('li').get(0);
var ajaxName = $li.className.match(/(?:^|\s)ajax-(.*?)(?:$|\s)/)[1];
Demo can be found here
Below kept for reference only
var ajaxName = 'ajax-first'.match(/(\w+)$/)[0];
alert(ajaxName);
Use the \w (word) pattern and bind it to the end of the string. This will force a grab of everything past the last hyphen (assuming the value consists of only [upper/lower]case letters, numbers or an underscore).
The non-regex approach could also use the String.split method, coupled with Array.pop.
var parts = 'ajax-first'.split('-');
var ajaxName = parts.pop();
alert(ajaxName);
you can try to replace ajax- with ""
I like the split method #Brad Christie mentions, but I would just do
function getLastPart(str,delimiter) {
return str.split(delimiter)[1];
}
This works if you will always have only two-part strings separated by a hyphen. If you wanted to generalize it for any particular piece of a multiple-hyphenated string, you would need to write a more involved function that included an index, but then you'd have to check for out of bounds errors, etc.
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"