Javascript regex, replacing numbers with manipulated number - javascript

I have the following string:
"4/7/12"
and I would like to replace each number with this formula:
(25 - x) where 'x' is the number from the string.
For example:
"4/7/12" would be translated into: "21/18/13"
How can I do this using 'replace()' and Regex ??
var player_move = "5/7/9";
var translated_pm = player_move.replace(/\/\*?/, 25 - /$1/);
Thank you!

Try this, all in one line:
var player_move = "5/7/9";
var new_move = player_move.split('/').map(function(number) { return 25 - Number(number); }).join('/');
alert(new_move);

Do you have to use a regex?
JsBin example
without regex
This might be a better way to do it:
var n = "4/7/12".split('/').map(function(el) {
return 25 - Number(el); // Number not needed here bc of coercion but I like it here
}).join('/');
regexp
With .replace, you can pass in a function like so:
var re = "4/7/12".replace(/\d+/g, function(match) {
return 25 - match;
})

Try this
var translated_pm = player_move.replace(/\d+/g, function (x){return 25 - parseInt(x)});

Related

JavaScript regex to search between strings

Hi I would like to search between strings using regex for JavaScript
String format:
saobjectid=tt-234,ou=info
saobjectid=bb-456,ou=info
saobjectid=bng,ou=info
saobjectid=asx 1 ert 7,ou=info
Expected output:
tt-234
bb-456
bng
asx 1 ert 7
I have tried this
[a-z]+[-,\s]+[0-9]+
But didn't manage to capture all different scenarios
Thanks for your help
Just added this answer to depict that it can also be done using substr in javascript:
var a = "saobjectid=tt-234,ou=info";
var b = "saobjectid=bb-456,ou=info";
var c = "saobjectid=bng,ou=info";
var d = "saobjectid=asx 1 ert 7,ou=info";
console.log(getSubstr(a));
console.log(getSubstr(b));
console.log(getSubstr(c));
console.log(getSubstr(d));
function getSubstr(a){
return a.substr(a.indexOf('=')+1, a.indexOf(',') - a.indexOf('=')-1);
};
a regex like =([-\s\w]+), will do.
Check it out at regex101 or here:
var s=`saobjectid=tt-234,ou=info
saobjectid=bb-456,ou=info
saobjectid=bng,ou=info
saobjectid=asx 1 ert 7,ou=info"`;
var regexp = /=([-\s\w]+),/g;
while ((match = regexp.exec(s)) != null){
console.log(match[1]);
}

In Javascript, how to find a character in a string and put all the characters before it in a variable

In javascript, I am trying to make a program that had to do with fractions that you can input and I need a function that will convert a fraction in this format( "10/27") to either 10 or 27 depending on user specification but I don't know how I would code this function. Any code or suggestions to get me started would be much appreciated.
You can search in string using indexOf(). It returns first position of searched string.
If you want to split string using a character in it, use split(). It will return an array. So for eg: in you string 27/10, indexOf / is 3 but if you do split, you will get array of 2 values, 27 and 10.
function splitString(str, searchStr) {
return str.split(searchStr);
}
function calculateValue(str) {
var searchStr = '/';
var values = splitString(str, searchStr);
var result = parseInt(values[0]) / parseInt(values[1]);
notify(str, result);
}
function notify(str, result) {
console.log(result);
document.getElementById("lblExpression").innerText = str;
document.getElementById("lblResult").innerText = result;
}
(function() {
var str = "27/10";
calculateValue(str)
})()
Expression:
<p id="lblExpression"></p>
Result:
<p id="lblResult"></p>
You can split the string into an array with split(), then take the first or second part as the numerator or denominator:
function getNumerator(fraction) {
// fraction = "10/27"
return fraction.split("/")[0];
}
function getDenominator(fraction) {
// fraction = "10/27"
return fraction.split("/")[1];
}
var fraction = "10/27".split("/");
var numerator = fraction[0];
var denominator = fraction[1];
You can of course use a library for it too: https://github.com/ekg/fraction.js
With this library the answer would be:
(new Fraction(10, 27)).numerator
Considering str contains the input value then,
a = str.substring(str.indexOf("/")+1);
b = str.substring(0, str.indexOf("/"));
Output:
if str is "10/17" then,
a == 17;
b == 10;

Parsing a String looking characters

I am trying to extract the numbers of this string: "ax(341);ay(20);az(3131);"
I think that I can do it how this:
var ax = data.split('(');
var ax2 = ax[1].split(')');
ax2[0] has "341"
Now If I can repeat this but starting in the next indexOf to take the second number.
I think that it's a bad practice, so I ask you If you have a better idea.
Thanks in advance
Use a regular expression:
var str = "ax(-341);ay(20);az(3131);"
var regex = /(-?\d+)/g
var match = str.match(regex);
console.log(match); // ["-341", "20", "3131"]
Now you can just access the numbers in the array as normal.
DEMO
You can use regex to extract all numbers from this.
var data = "ax(341);ay(20);az(3131);";
var ax = data.match(/\d+/g);
Here ax is now ["341", "20", "3131"]
Note that ax contains numbers as string. To convert them to number, use following
ax2 = ax.map( function(x){ return parseInt(x); } )
EDIT: You can alternatively use Number as function to map in the line above. It'll look like,
ax2 = ax.map( Number )
After this ax2 contains all the integers in the original string.
You could use a regular expression, eg:
var string = 'ax(341);ay(20);az(3131);';
var pattern = /([0-9]{1,})/g;
var result = string.match(pattern);
console.log(result);
// ["341", "20", "3131"]
http://regex101.com/r/zE9pS7/1

Regex to capture whole word with specific beginning

I need to capture a number passed as appended integers to a CSS class. My regex is pretty weak, what I'm looking to do is pretty simple. I thought that "negative word boundary" \B was the flag I wanted but I guess I was wrong
string = "foo bar-15";
var theInteger = string.replace('/bar\-\B', ''); // expected result = 15
Use a capture group as outlined here:
var str= "foo bar-15";
var regex = /bar-(\d+)/;
var theInteger = str.match(regex) ? str.match(regex)[1] : null;
Then you can just do an if (theInteger) wherever you need to use it
Try this:
var theInteger = string.match(/\d+/g).join('')
string = "foo bar-15";
var theInteger = /bar-(\d+)/.exec(string)[1]
theInteger // = 15
If you just want the digits at the end (a kind of reverse parseInt), why not:
var num = 'foo bar-15'.replace(/.*\D+(\d+)$/,'$1');
or
var m = 'foo bar-15'.match(/\d+$/);
var num = m? m[0] : '';

javascript get characters between slashes

Can someone please help. I need to get the characters between two slashes e.g:
Car/Saloon/827365/1728374
I need to get the characters between the second and third slashes. i.e 827365
You can use the split() method of the String prototype, passing in the slash as the separator string:
const value = 'Car/Saloon/827365/1728374';
const parts = value.split('/');
// parts is now a string array, containing:
// [ "Car", "Saloon", "827365", "1728374" ]
// So you can get the requested part like this:
const interestingPart = parts[2];
It's also possible to achieve this as a one-liner:
const interestingPart = value.split('/')[2];
Documentation is here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
This will simply alert 1728374, as you want
alert("Car/Saloon/827365/1728374".split('/')[3]);
or, a bit longer, but also more readable:
var str = "Car/Saloon/827365/1728374";
var exploded = str.split('/');
/**
* str[0] is Car
* str[1] is Saloon
* str[2] is 827365
* str[3] is 1728374
*/
Try the_string.split('/') - it gives you an array containing the substrings between the slashes.
try this:
var str = 'Car/Saloon/827365/1728374';
var arr = str.split('/'); // returns array, iterate through it to get the required element
Use split to divide the string in four parts:
'Car/Saloon/827365/1728374'.split('/')[2]
Gives "827365"
You will have to use the .split() function like this:
("Car/Saloon/827365/1728374").split("/")[2];
"Car/Saloon/827365/1728374".split("/")[2]
"Car/Saloon/827365/1728374".split("/")[3]
How many you want you take it.. :)
var str = "Car/Saloon/827365/1728374";
var items = str.split("/");
for (var i = 0; i < items.length; i++)
{
alert(items[i]);
}
OR
var lastItem = items[items.length - 1]; // yeilds 1728374
OR
var lastItem1728374 = items[2];

Categories