jquery add 1 to string - javascript

Having this
class="row45"
I would like to make it "row46" using jquery or simple javascript
Tried something like this:
var row = $(this).parents('tr').prev();
var rclass = row.attr('class');
var class_number = rclass.match(/(\d+)/g);
but that only gave me the number 45.

Take that string, convert it to a number, and add one
var class_number = rclass.match(/(\d+)/g)[0];
var num = parseInt(class_number, 10) + 1;
console.log(num); //46
another way with replace
var nextClass = rclass.replace(/(\d+)/g, function(a){ return parseInt(a,10) + 1; });
console.log(nextClass); //row46

You did:
var row = $(this).parents('tr').prev();
var rclass = row.attr('class');
var class_number = rclass.match(/(\d+)/g);
After this simply do:
class_number = parseInt(class_number) + 1;
rclass = "row"+class_number;
row.attr("class", rclass);
And that row will now have class "row46" and rclass will have string "row46".

I've used String.replace(regexp, function) for this kind of thing.
// returns "row46"
"row45".replace(/(\d+)/, function(theString, theNumber) {
return (+theNumber) + 1;
});

Related

concat two variable and find array value position using javascript

I have array object like this below
var TTP01[2,0,0,0,0,0,4,6,1,4,0,9,1]
If I assign TTP01[0] like this, I will get Output 2. This is working fine.
But I'm getting values separately and I need to assign the Object.
object = TTP;
count =01;
xy = x*y;
I concat like this below
var obj = objname.concat(count, "[", xy, "]");
console.log( obj );
In console log, I'm getting like this TTP01[0].
But want to get output 2
Please help me... Thanks
This will work.
eval(objname + count)[xy]
fullcode:
var TTP01 = [2,0,0,0,0,0,4,6,1,4,0,9,1];
var objname = "TTP";
var count = "01";
var xy = 0;
console.log(eval(objname + count)[xy]); // 2
You can try like this way,
var TTP01 = [2,0,0,0,0,0,4,6,1,4,0,9,1];
var objname = 'TTP';
var count = '01';
xy = 0;
var obj = window[objname + count];
console.log( obj[xy] );
Assign TTP01 to some base object :
var base = {
TTP01: [2,0,0,0,0,0,4,6,1,4,0,9,1]
}
var objname = 'TTP';
var count = '01';
var objStr = objname + count;
var xy = 0;
console.log(base[objStr][xy])

RegExpr and variable

I have just one question maybe stupid (like every day)
var word = []; (an array with 100 words for example)
var tab = []; // resultat
var root = "test";
var debut = "Anti";
var reg1=new RegExp("^"+debut + "+." + root,"g")
for(var i = 0;i<word.length; i++){
// a word begin with Anti and contain test pls
if (word[i].match(reg1)){ยด
tab.push(word[i])
}
}
console.log(tab.join(', ');
but it is dont work, i dont know how to use variable with regexpr, thanks, sorry for my english
var r = new RegExp('anti.*esis', 'ig')
document.write('antithesis'.match(r), '<br/>') // ["antithesis"]
document.write('antihero'.match(r), '<br/>') // null
Here is the code, but is used the test() instead of match()
var word=["yea","antiboyahtest","antigssjshbztest"];
var debut="anti";
var root="test";
var reg=new RegExp("^"+debut+".*"+root,"g");
var tabs=[];
for(i in word){
if(reg.test(word[i])){
tabs.push(word[i]);
}
}
alert(tabs);
The solution using RegExp.test and Array.filter functions:
var word = ['Antitest', 'Antidot', 'Anti-next-test', 'testAnti'],
root = "test", debut = "Anti",
reg1 = new RegExp("^"+debut + ".*?" + root, "g");
var result = word.filter(function (w) {
return reg1.test(w);
});
console.log(result); // ["Antitest", "Anti-next-test"]
Also, there's an additional approach using Array.indexOf function without any regex which will give the same result:
...
var result = word.filter(function (w) {
return w.indexOf(debut) === 0 && w.indexOf(root) !== -1;
});

Javascript string manipulation url

My problem is I am trying to extract certain things from the url. I am currently using
window.location.href.substr()
to grab something like "/localhost:123/list/chart=2/view=1"
What i have now, is using the index positioning to grab the chart and view value.
var chart = window.location.href.substr(-8);
var view = window.location.href.substr(-1);
But the problem comes in with I have 10 or more charts. The positioning is messed up. Is there a way where you can ask the code to get the string between "chart=" and the closest "/"?
var str = "/localhost:123/list/chart=2/view=1";
var data = str.match(/\/chart=([0-9]+)\/view=([0-9]+)/);
var chart = data[1];
var view = data[2];
Of course you may want to add in some validation checks before using the outcome of the match.
Inspired by Paul S. I have written a function version of my answer:
function getPathVal(name)
{
var path = window.location.pathname;
var regx = new RegExp('(?:/|&|\\?)'+name+'='+'([^/&,]+)');
var data = path.match(regx);
return data[1] || null;
}
getPathVal('chart');//2
Function should work for fetching params from standard get parameter syntax in a URI, or the syntax in your example URI
Here's a way using String.prototype.indexOf
function getPathVar(key) {
var str = window.location.pathname,
i = str.indexOf('/' + key + '=') + key.length + 2,
j = str.indexOf('/', i);
if (i === key.length + 1) return '';
return str.slice(i, j);
}
// assuming current path as described in question
getPathVar('chart');
You could split your string up, with "/" as delimiter and then loop through the resulting array to find the desired parameters. That way you can easily extract all parameters automatically:
var x = "/localhost:123/list/chart=2/view=1";
var res = {};
var spl = x.split("/");
for (var i = 0; i < spl.length; i++) {
var part = spl[i];
var index = part.indexOf("=");
if (index > 0) {
res[part.substring(0, index)] = part.substring(index + 1);
}
}
console.log(res);
// res = { chart: 2, view: 1}
FIDDLE

Want to get specific value from string

I have a JavaScript string sentrptg2c#appqueue#sentrptg2c#vwemployees#.
I want to get last string vwemployees through RegExp or from any JavaScript function.
Please suggest a way to do this in JavaScript.
You can use the split function:
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
str = str.split("#");
str = str[str.length-2];
alert(str);
// Output: vwemployees
The reason for -2 is because of the trailing #. If there was no trailing #, it would be -1.
Here's a JSFiddle.
var s = "...#value#";
var re = /#([^#]+)#^/;
var answer = re.match(s)[1] || null;
if you're sure the string will be separated by "#" then you can split on # and take the last entry... I'm stripping off the last #, if it's there, before splitting the string.
var initialString = "sentrptg2c#appqueue#sentrptg2c#vwemployees#"
var parts = initialString.replace(/\#$/,"").split("#"); //this produces an array
if(parts.length > 0){
var result = parts[parts.length-1];
}
Try something like this:
String.prototype.between = function(prefix, suffix) {
s = this;
var i = s.indexOf(prefix);
if (i >= 0) {
s = s.substring(i + prefix.length);
}
else {
return '';
}
if (suffix) {
i = s.indexOf(suffix);
if (i >= 0) {
s = s.substring(0, i);
}
else {
return '';
}
}
return s;
}
No magic numbers:
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
var ar = [];
ar = str.split('#');
ar.pop();
var o = ar.pop();
alert(o);
jsfiddle example

How to increment number in string using Javascript or Jquery

The id of my textarea is string and of this format
id='fisher[27].man'
I would like to clone the textarea and increment the number and get the id as fisher[28].man and prepend this to the existing textarea.
Is there a way to get this done easily with jquery?
var existingId = $("#at textarea:last").attr('id');
var newCloned = lastTextArea.clone();
var newId = newCloned.attr('id');
//add the index number after spliting
//prepend the new one to
newCloned.prepend("<tr><td>" + newCloned + "</td></tr>");
There has to be easier way to clone, get index number, split and prepend.
I'm have also tried to do this with regEx
var existingIdNumber = parseInt(/fisher[(\d+)]/.exec(s)[1], 10);
Can anybody help me with this?
Correct regex would be this
/fisher\[\d+\].man/
Here is a way through through which you would extract the the id.
id = text.replace(/fisher\[(\d+)\].man+/g,"$1");
//Now do whatever you want with the id
Similarly, Same replacement technique can be used to get an incremented id as:
existingId = 'fisher[27].man';
newId = existingId .replace(/(\d+)+/g, function(match, number) {
return parseInt(number)+1;
});
console.log(newId);
Demo with both usage
jsFiddle Demo
No need for all the extra code. Change this line:
var newId = newCloned.attr('id');
To:
var newId = newCloned.attr('id').replace( /(\d+)/, function(){return arguments[1]*1+1} );
Another easy solution from this question's accepted answer:
'url1'.replace(/\d+$/, function(n){ return ++n }); // "url2"
'url54'.replace(/\d+$/, function(n){ return ++n }); // "url55"
Very clean and readable.
If your Id has this format
id='fisher[27].man'
You can do something like this
var startIndex = newId.indexOf('[');
var endIndex = newId.indexOf(']');
var number = parseInt(newId.substr(startIndex + 1, endIndex - startIndex - 1));
var incrementedId = number + 1; // 28
where
var newId = newCloned.attr('id');
I am amazed that there is not any good implementation for this simple thing. All of the examples forget the case of having zeroes before the number. The code below should take care of that.
// 'item001' => 'item002'
function increment_alphanumeric_str(str){
var numeric = str.match(/\d+$/)[0];
var prefix = str.split(numeric)[0];
function increment_string_num(str){
var inc = String(parseInt(str)+1);
return str.slice(0, str.length-inc.length)+inc;
}
return prefix+increment_string_num(numeric);
}
Example:
> increment_alphanumeric_str('test09')
'test10'
Only drawback is that this will break if we have something like 'test99'.
You can do this pretty easily with a regex replacement:
var id = "fisher[27].man";
id = id.replace(/\[(\d+)\]/, function(match, number) {
return '[' + (parseInt(number, 10) + 1) + ']';
});
// id is now "fisher[28].man"

Categories