Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have an expression such as xsin(x) it is valid only if * comes between x and sin(x) and make it as x*sin(x)
my idea is first search for x then insert * between x and another variable if there is a variable.
equation
sin(x)cos(x) to sin(x)*cos(x)
pow((x),(2))sin(x)to pow((x),(2))*sin(x)
sin(x)cos(x)tan(x) to sin(x)*cos(x)*tan(x)
etc
I am trying with this code..
function cal(str)
{
//var string = "3*x+56";
var regex = /([a-z]+)\(\(([a-z]+)\),\(([0-9]+)\)\)\(([a-z0-9\*\+]+)\)([\*\-%\/+]*)/;
var replacement = "$1($2($4),($3))$5";
while(str.match(regex))
{
str = str.replace(regex,replacement);
}
return str;
}
This one matches right parentheses followed by a letter (e.g. )s ), and inserts a * (e.g. )*s )
It also replaces x followed by a letter with x* and that letter
It should work for x+sin(x) and xsin(x)
function addStars(str) {
return str.replace(/(\))([A-Za-z])/g,function(str, gr1, gr2) { return gr1 + "*" + gr2 }).replace(/x([A-Za-wy-z])/g,function(str, gr1) { return "x*" + gr1 })
}
document.write(addStars("x+sin(x)tan(x)ln(x)+xsin(x)"))
Help from:
JavaScript - string regex backreferences
qwertymk's answer
> 'sin(x)cos(x)'.replace(/(?!^)\w{3}/g, '*$&')
< "sin(x)*cos(x)"
> 'pow((x),(2))sin(x)'.replace(/(?!^)\w{3}/g, '*$&')
< "pow((x),(2))*sin(x)"
> 'sin(x)cos(x)tan(x)'.replace(/(?!^)\w{3}/g, '*$&')
< "sin(x)*cos(x)*tan(x)"
This says: replace anything that doesn't start at the beginning and has three letters with a * and everything that matched
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I need to replace 02:04.887004 to 02:04.887 with jquery or js.
Other times I have microseconds just with four decimals (02:04.8348) and I would have 02:04.834
I would use regexp to find $:[d][d].$ and then return it but with the three decimals
If the length of the string is reliable, you can just trim the unwanted characters from the string, e.g.
let time = '02:04.887004';
// If format is reliable, get first 9 characters
console.log(time.substr(0,9));
// If length might vary and number of decimals is at least 3
// Trim from end
console.log(time.slice(0, -(time.length - time.indexOf('.') - 4)))
// Trim from start
console.log(time.substr(0, time.length - time.indexOf('.') + 2));
If the format is more unreliable, you have more work to do.
You can use a regular expression or a split function or a substring on the string to format your timestring. Here is an example of the three:
const time = '02:04.887004';
const regex = /[\d]{2}:[\d]{2}\.[\d]{3}/
const formatTime = time => {
const match = time.match(regex);
return match ? match[0] : match;
}
const formatTime2 = time => {
const m = time.split(':').shift();
const s = time.split(':').pop().split('.').shift();
const ms = time.split('.').pop().substr(0,3);
return m + ':' + s + '.' + ms;
}
const formatTime3 = time => {
return time.substr(0,9);
}
console.log(formatTime(time));
console.log(formatTime2(time));
console.log(formatTime3(time));
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I see questions asked on truncating the leading zeros, but nothing found to solve my issue. I have a array of strings representing days returning from an api call.
Ex:
arr= ["061-094", "0561-0960", "000-005", "180+"];
arr.map(function(d){
<div>{d} days</div> // this returns 061-094 days
});
1) How can I remove the leading zeros so that it displays like:
61-94 days
561-960 days
0-5 days
2) How can display:
more than 180 days
for "180+" value?
Thanks
You can use map to generate a new array by testing each value, and if it matches the nn-nn pattern, split the string into numbers, convert to number (removes leading zeros but keeps "0" as a single value), then put them back as strings.
If the string matches the nn+ pattern, process it accordingly.
E.g.
var arr = ["061-094", "0561-0960", "000-005", "180+"];
var result = arr.map(function(v) {
// deal with nn-nn
if (/\d+-\d+/.test(v)) {
return v.split('-').map(s => +s).join('-');
}
// Deal with nn+
if (/\d+\+/.test(v)) {
return v.replace(/(\d+).*/, 'more than $1 days');
}
});
console.log(result);
If you want to wrap in HTML, then do that too.
Assuming there's no other patterns in your data than 000-000 or 180+:
arr = ["061-094", "0561-0960", "000-005", "180+", "90+"];
var result = arr.map(function(d){
if (d.substr(-1) == "+") {
return "<div>More than " + d.slice(0,-1) + " days</div>";
}
var parts = d.split("-");
var truncatedParts = [];
parts.map(function(part) {
truncatedParts.push(parseInt(part, 10));
});
return "<div>" + truncatedParts.join("-") + " days</div>" ;
});
console.log(result);
Have you tired making a String to remove all leading zeros?
String strPattern = "^0+";
This should remove all leading zeros but not trailing zeros.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to make an algorithm, for a NodeJS app, that converta any given string to a 1 to 3 digit number (better if the number is between 1-500).
e.g
ExampleString -> 214
Can anyone help me find a good solution?
EDIT:
I want to get a crime coefficient number from a username (string).
Ok, you can use JS function to get charCode of letter
let str = "some string example";
let sum = 0;
for (let i=0; i<str.length; i++) {
sum += parseInt(str[i].charCodeAt(0), 10); // Sum all codes
}
// Now we have some value as Number in sum, lets convert it to 0..1 value to scale to needed value
let rangedSum = parseFloat('0.' + String(sum)); // Looks dirty but works
let resultValue = Math.round(rangedSum * 500) + 1; // Same alogorythm as using Math.random(Math.round() * (max-min)) + min;
I hope it helps.
So as you are using nodejs, you can use crypto library to get md5 hash of string and then get it as HEX.
const crypto = require('crypto');
let valueHex = crypto.createHash('md5').update('YOUR STRING HERE').digest('hex');
// then get it as decimal based value
let valueDec = parseInt(valueHex, 16);
// and apply the same algorythm as above to scale it between 1-500
function coeficient() {
return Math.floor(Math.random() * 500) + 1;
}
console.log(coeficient());
console.log(coeficient());
console.log(coeficient());
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have an string of numbers "123456" i want to split them in all possible ways.
So
1 23456
1 2 3456
1 23 45 6
1234 5 6
and so on
What i have tried...
looping over len-1, and splitting on every index, but logically it misses a lot of possible scenarios.
You could try a recursive function like below...
<script lang="javascript">
// Split string into all combinations possible
function splitAllWays(result, left, right){
// Push current left + right to the result list
result.push(left.concat(right));
//document.write(left.concat(right) + '<br />');
// If we still have chars to work with in the right side then keep splitting
if (right.length > 1){
// For each combination left/right split call splitAllWays()
for(var i = 1; i < right.length; i++){
splitAllWays(result, left.concat(right.substring(0, i)), right.substring(i));
}
}
// Return result
return result;
};
var str = "123456";
var ans = splitAllWays([], [], str);
</script>
Results
123456
1,23456
1,2,3456
1,2,3,456
1,2,3,4,56
1,2,3,4,5,6
1,2,3,45,6
1,2,34,56
1,2,34,5,6
1,2,345,6
1,23,456
1,23,4,56
1,23,4,5,6
1,23,45,6
1,234,56
1,234,5,6
1,2345,6
12,3456
12,3,456
12,3,4,56
12,3,4,5,6
12,3,45,6
12,34,56
12,34,5,6
12,345,6
123,456
123,4,56
123,4,5,6
123,45,6
1234,56
1234,5,6
12345,6
I think that is the right results (32 combinations). Can someone confirm?
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have the following syntax.
var name = [Name_is][234]
var number = find [234];
How can i find this number in javascript/jquery which is inside [] ?
Use a regular expression.
var string = "[Name_is][234]"
var matches = string.match(/\[(\d+)]/);
if (matches.length) {
var num = matches[1];
}
Check out a working fiddle: http://jsfiddle.net/rEJ5V/, and read more on the String.match() method.
if you want to extract the text between the [ ], you can do:
var name = "[Name_is][234]";
var check= "\{.*?\}";
if (name.search(check)==-1) { //if match failed
alert("nothing found between brackets");
} else {
var number = name.search(check);
alert(number);
}