How to increment number in string using Javascript or Jquery - javascript

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"

Related

Javascript method to convert string value

Can someone please help me to write a JS method which takes a String value like
/Content/blockDiagram/0/bundle/0/selectedBundle
/Content/blockDiagram/1/bundle/1/selectedBundle
/Content/blockDiagram/0/bundle
and convert it to
/Content/blockDiagram[1]/bundle[1]/selectedBundle
/Content/blockDiagram[2]/bundle[2]/selectedBundle
/Content/blockDiagram[1]/bundle
It is basically taking the number in the path and increment it by 1 and then changing the structure of the string.
My attempt
function setReplicantPartListOptions(list) {
list = "/" + list;
var index = list.lastIndexOf("/");
var tempString = list.substring(0, index);
var index2 = tempString.lastIndexOf("/");
var initialString = list.substring(0, index2);
var result = tempString.substring(index2 + 1, index) var middlevalue = parseFloat(result) + 1
var lastString = list.substring(index, list.length);
list = initialString + "[" + middlevalue + "]" + lastString;
return list;
}
simple regular expression with capture group with replace
var str = "/Content/blockDiagram/0/bundle/0/selectedBundle"
var updated = str.replace(/\/(\d+)/g, function (m, num) {
var next = +num + 1; // convert string to number and add one
return "[" + next + "]"; //return the new string
})
console.log(updated)
String.replace(RegExp, callback(match, contents)) is the callback version of String.replace().
In my case, the first parameter of callback function is the result/match. It takes the match and converts it to number using + operator, and then increment it by one. Finally, I add [ ] around the value and return it!
let str = "/Content/blockDiagram/0/bundle/0/selectedBundle"
console.log(
str.replace(/\b\d+\b/g, match => `[${ +match + 1 }]`)
);
var str = "/Content/blockDiagram/0/bundle/0/selectedBundle"
console.log(
str.replace(/\/(\d+)\//g, function(_,num) { return `[${++num}]`})
)

Javascript-split() not working when there are repeated chars in a string

Not sure how valid is this approach, but I'm unable to split the string into 2 when there are repeated characters.
var match = 's';
var str = "message";
var res = str.split(match, 2);
For instance i tried to use split() on the string "message", it results into:
me,""
So i did this:
res = str.split(match, 3);
so now it resulted into:
me,,age
but as you can see im still missing the second 's' in the "message" string. what im trying to get is I'm passing a matched character (in above case var match which is dynamically generated) to the split() and splitting into 2. I was hoping to get something this:
res = me,,sage
is that possible using split() or is there a better method to achieve this?
P.S: in fiddle i've given another string eg: (string = "shadow") which works fine.
Fails only when there are repeated letters in the string!
fiddle: https://jsfiddle.net/ukeeq656/
EDIT::::::::::::
Thanks everyone for helping me out on this...and so sorry for last min update on the input, i just realized that var match; could be a word too, as in var match = 'force'; and not just var match ='s'; where the string is "forceProduct", so when my match is more than just a letter, this approach works: str.split(match, 2);, but str.indexOf(match); doesnt obviously... could there be an approach to split: "","Product". My extreme apologies for not mentioning this earlier.any help on this would be appreciated!!
eg fiddle:
https://jsfiddle.net/ukeeq656/3/
I don't think split() is the correct way to do this.
Please see below:
var match = 's';
var str = "message";
var index = str.indexOf(match);
var res =[];
res[0] = str.substring(0, index);
res[1] = " ";
res[2] = str.substring(index + 1);
console.log(res);
I'm not sure what your end goal is but I think this gets you what you want.
var match = 's';
var str = "message";
var index = str.indexOf(match);
var res = str.substring(0, index) + ',' + str.substring(index + 1);
alert(res); // me,sage
You could write a function to do this;
function newSplit(str, match) {
var num = str.indexOf(match);
var res = [];
res.push(str.substring(0, num));
//res.push(str.substring(num + 1, str.length)); // this line has been modified
res.push(str.substring(num + match.length, str.length));
return res;
}
var match = 'force';
var str = 'forceProduct';
console.log(newSplit(str, match));
This is what you want?

jquery add 1 to string

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;
});

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

replace HTML text with incrementing numbers in javascript

I have a bunch of text with no HTML, and I'm trying to find all replace all instances of String with <span id="x">String</span>
The catch is I'm trying to increment x every time to get a bunch of uniquely identifiable spans rather then identical ones.
I have no problem getting all instances of String, but for the life of me I can't get the increment to work. All help I can find seems to be directed towards doing the opposite of this.
Any ideas what I can do or where else to turn for help?
EDIT:
This is targeting a div with ID 'result' that contains only text.
var target = "String";
var X = //the number I was trying to increment
var re = new RegExp(" " + target + " ","g");
document.getElementById('result').innerHTML = document.getElementById('result').innerHTML.replace(re, '<span id="' + X + '">' + target + '</span>');
I'm guessing you are using a regex, which is fine, but you can specify a function as the second parameter to replace and do your logic there.
The MDN documentation for doing this is here - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter
You could use something like this:
http://jsfiddle.net/gjrCN/2/
function replacer(orig, target) {
var x = 0;
var re = new RegExp(target, "g");
var ret = orig.replace(re, function (match) {
return "<span id='" + (++x) + "'>" + match + "</span>";
});
return ret;
}
var example = "String Stringasdf String2344 String";
var replaced = replacer(example, "String");
console.log(replaced);
You can change ++x to x++ if you want the counting to start at 0 instead of 1.
With reference to these docs.
You can pass a function to the String.replace method would allow you to increment a counter with each call and use that to set your ID:
var forReplacements = "I do like a String that's a nice long String with Strings in it";
var incrementer = (function() {
var counter = -1;
var fn = function(match) {
counter++;
return "<span id='"+counter+"'>"+match+"</span>";
};
fn.reset = function() {
counter = -1;
}
return fn;
}());
var newString = forReplacements.replace(/String/g, incrementer )
See this fiddle to see it in action

Categories