Replace any number with a specific number from variable - javascript

I have link like this foo.net/index.php?page=15
And I need to replace any number after page=xxx and get the new number from variable
This my current code just replace 15 to 16
var num = 16,
// What if the str = foo.net/index.php?page=10
str = 'foo.net/index.php?page=15',
n = str.replace('15',num);
$('span').html(n);
You can check the code in http://jsfiddle.net/KMsv7/

If you want to select and replace numbers in a string you can use regular expression:
// Replacing macting number with the specified value
var n = str.replace(/\d+/, num);
In case that you want to add/subtract/divide/multiply the matching value, you can also use the callback function of the .replace() method:
var n = str.replace(/\d+/, function(number) {
return number + 1;
});
Reference.

Related

Custom Regular Expression that will replace a segment of a string based on number and value

I would like to do is to come up with a custom Javascript function, that when a user calls to a string, will replace a segment of a string based on a number and a value
The number tells the function which segment value should be replaced after the Nth hyphen.
The value tells the function what the new string value replacement will be.
For example:
var x = '4-D-5200-P41-120-08C2-8131-0000-9'
var str = RepFinCode(x,2,'ABCD")
Therefore, after some processing...
str = '4-D-ABCD-P41-120-08C2-8131-0000-9'
This should do it:
var x = '4-D-5200-P41-120-08C2-8131-0000-9';
var n = 3;
var s = 'ABCD';
var r = new RegExp('(([^-]+-){' + n + '})[^-]+-');
document.getElementById('a').innerHTML = x.replace(r, '$1' + s + '-');
<div id='a'></div>
As stated in the comments, this is probably not the way to go - it doesn't shorten the code, is not faster, and not more readable.

Javascript getting number from string

I have a string:
var example = 'sorted-by-' + number;
Where number variable can be any positive integer. I don't know how to reverse this process, not knowing how many digits this number has. I want to get from example string a number at the end.
var outputNumber = example.substring(10);
This is the simple solution because example string always start with 'sorted-by-'.
let num = + string.substr(10);
You can use String#replace function to replace sorted-by- to empty string and after that convert left part to a number:
var example = 'sorted-by-' + 125;
var num = +example.replace('sorted-by-', '');
console.log(num);
You can split string at - and get last element using pop().
var example = 'sorted-by-' + 100.99
var n = +(example.split('-').pop())
console.log(n)
You can also use regex for this.
var number = 245246245;
var example = 'sorted-by-' + number;
var res = example.match(/^sorted-by-(\d+)/);
console.log(+res[1]);

How to get ASCII of number in JavaScript?

I am aware of name.charCodeAt(0). I am having issued with the following code, so I want a solution for below.
var number= 2;
var t = number.charCodeAt(0);
console.log(t);
The answer needs to be in ASCII. I am getting the log as 2 and not as ASCII value 50. What can be the issue?
ASCII is a way of representing String data. You need to first convert your Number to String;
Remember also that String can have arbitrary length so you'll need to iterate over every character.
var x = 2,
str_x = '' + x,
chrs = Array.prototype.map.call(str_x, function (e) {return e.charCodeAt(0);});
chrs; // [50]
Finally, JavaScript works with UTF-16/UCS-2 and not plain ASCII. Luckily the values for digits are the same in both so you don't have to do any further transformation here.
You have to cast a number to a string first to use .charCodeAt to get the numerical character code.
var number = 2;
var t = String( number ).charCodeAt( 0 );
console.log( t ); // 50
Just convert the number to String and call the method on it.
var number = 2;
var numberInString = number.toString();
var code = numberInString.charCodeAt(0);
console.log(code);

How to increment a string in Javascript

Let's say I have the following string:
aRandomString
I'm then checking my database to see if that string has been used before (or if there's any string that starts with the given one). If it has, I'd like to increment it. The result would be the following:
aRandomString1
If that string exists, it would become aRandomString2, and so on. I'm assuming I need to complete the following steps: 1. Check for trailing numbers or set to 0, 2. Increment those trailing numbers by 1, append that number to the original string. Just trying to figure out a solid way to accomplish this!
Update
This is what I have so far:
var incrementString = function( str ){
var regexp = /\d+$/g;
if( str.match(regexp) )
{
var trailingNumbers = str.match( regexp )[0];
var number = parseInt(trailingNumbers);
number += 1;
// Replace the trailing numbers and put back incremented
str = str.replace(/\d+$/g , '');
str += number;
}else{
str += "1";
}
return str;
}
I feel like this should be easier though.
function incrementString(str) {
// Find the trailing number or it will match the empty string
var count = str.match(/\d*$/);
// Take the substring up until where the integer was matched
// Concatenate it to the matched count incremented by 1
return str.substr(0, count.index) + (++count[0]);
};
If the match is the empty string, incrementing it will first cast the empty string to an integer, resulting the value of 0. Next it preforms the increment, resulting the value of 1.
I had to keep the leading zeros in the number, this is how I did it:
function incrementString (string) {
// Extract string's number
var number = string.match(/\d+/) === null ? 0 : string.match(/\d+/)[0];
// Store number's length
var numberLength = number.length
// Increment number by 1
number = (parseInt(number) + 1).toString();
// If there were leading 0s, add them again
while (number.length < numberLength) {
number = "0" + number;
}
return string.replace(/[0-9]/g, '').concat(number);
}

how to get numeric value from string?

This will alert 23.
alert(parseInt('23 asdf'));
But this will not alert 23 but alerts NaN
alert(parseInt('asdf 23'));
How can I get number from like 'asd98'?
You can use a regex to get the first integer :
var num = parseInt(str.match(/\d+/),10)
If you want to parse any number (not just a positive integer, for example "asd -98.43") use
var num = str.match(/-?\d+\.?\d*/)
Now suppose you have more than one integer in your string :
var str = "a24b30c90";
Then you can get an array with
var numbers = str.match(/\d+/g).map(Number);
Result : [24, 30, 90]
For the fun and for Shadow Wizard, here's a solution without regular expression for strings containing only one integer (it could be extended for multiple integers) :
var num = [].reduce.call(str,function(r,v){ return v==+v?+v+r*10:r },0);
parseInt('asd98'.match(/\d+/))
function toNumeric(string) {
return parseInt(string.replace(/\D/g, ""), 10);
}
You have to use regular expression to extract the number.
var mixedTextAndNumber= 'some56number';
var justTheNumber = parseInt(mixedTextAndNumber.match(/\d+/g));
var num = +('asd98'.replace(/[a-zA-Z ]/g, ""));

Categories

Resources