How to separate these strings using javascript - javascript

I have collection of string like '36*' , '95' , '103*', '1001*' , '2301'.
I want to separate these into two parts the numerical part into integer and the asterisks part.
eg: take 36 from first, 95 from second, 103 from third and so on. I add them all. If asterisk is found then multiply the number with some factor.
The asterisk is always at the end.

You can extract out the parts you need using a regex.
var values = ['36*', '95', '103*', '1001*', '2301'];
var parts = values.map(function(x) {
var match = /(\d+)(\/|\*|\+|\-)?/.exec(x);
return {
numericPart: match[1],
operator: match[2]
};
});
You can then access the numeric or operator part for each element in your original array. i.e. parts[2].numericPart == 95
The regex (\d+)(\/|\*|\+|\-)? can be broken down as follows;
(\d+) - matches 1 or more digits and stores them in capture group 1
(\/|\*|\+|\-)? - matches a /*+- and stores it in capture group 2, this matches 0 or 1 times

This function will take an input and will return the number & special symbol(*).
function _seperateNum(value){
var returnObj={}; // This object will contain number * special character(if)
var replaceChar="";
if(value.indexOf("*") !=-1){ // check if input has *
replaceChar = value.replace(/[*]/g, ''); // replace it
returnObj.num = parseInt(replaceChar); // convert to number
returnObj.char = "*";
}
else{ // if no special charcater
returnObj.num = parseInt(value);
}
return returnObj;
}
var a =_seperateNum("36*");
console.log(a.num);
Jsfiddle

var
arr = ['36*' , '95' , '103*', '1001*' , '2301'],
sum = 0;
for (var i in arr) {
var item = arr[i];
sum += parseInt(item.indexOf('*') != -1 ? item.replace('*', '') : item);
}
alert(sum);

var arr = ['36*' , '95' , '103*', '1001*' , '2301'];
var t = [];
var f = [];
arr.forEach(function(e){if(e.indexOf("*") > 0){ t.push(e) } else { f.push(e) } } );
console.log(t); //asterisk values
#=> ["36*", "103*", "1001*"]
console.log(f); // other value
#=> ["95", "2301"]
if you want to multiple the each element of the array of asterisk elements to a factor like 10
arr.forEach(function(e){if(e.indexOf("*") > 0){ t.push(parseInt(e)* 10) } else { f.push(parseInt(e)) } } );
console.log(t); //asterisk values
#=> [360, 1030, 10010]
console.log(f); // other value
#=> [95, 2301]

Related

Set the last number in a string to negative

I have a string with diffrent mathematical characters, and i want to make the last number negative/positive. Let's say the string is "100/5*30-60+333". The result i want is "100/5*30-60+(-333)", and i want to convert it back to positive ("100/5*30-60+333").
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = hiddenText.value;
n.split('+');
n.split('-');
n.split('*');
n.split('/');
console.log(n);
}
What i get is the whole hiddenText.value, and not an array of all numbers. Any tips?
First, I'd match all of the basic math operators to get their order:
const operatorsArr = n.match(/\+|\-|\/|\*/g)
Then, split the string:
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = hiddenText.value;
n = n.replace(/\+|\-|\/|\*/g, '|');
n = n.split('|');
console.log(n);
}
Then, you will have an array of numbers, in which you can mutate the last number easily:
n[n.lengh-1] *= -1;
Now we can combine the two arrays together:
let newArr;
for (let i = 0; i < n.length; i++) {
newArr.push(n[i]);
if (operatorsArr[i]) newArr.push(operatorsArr[i]);
}
At last, you can rejoin the array to create the new String with a seperator of your choosing. In this example I'm using a space:
newArr = newArr.join(' ')
Please let me know how that works out for you.
Let's say the string is "100/5*30-60+333". The result i want is
"100/5*30-60+(-333)", and i want to convert it back to positive
("100/5*30-60+333").
The following code does that:
let mathStr = '100/5*30-60+333';
console.log(mathStr);
let tokens = mathStr.split('+');
let index = tokens.length - 1;
let lastToken = tokens[index];
lastToken = '('.concat('-', lastToken, ')');
let newMathStr = tokens[0].concat('+', lastToken);
console.log(newMathStr); // 100/5*30-60+(-333)
console.log(mathStr); // 100/5*30-60+333
EDIT:
... and i want to convert it back to positive ("100/5*30-60+333").
One way is to declare mathStr (with the value "100/5*30-60+333") as a var at the beginning and reuse it, later as you need. Another way is to code as follows:
let str = "100/5*30-60+(-333)";
str = str.replace('(-', '').replace(')', '');
console.log(str); // 100/5*30-60+333
To get numbers You can use replace function and split check code bellow :
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = "100/5*30-60+333";
n = n.replace('+','|+');
n = n.replace('-','|-');
n = n.replace('*','|*');
n = n.replace('/','|/');
n=n.split('|');console.log(n);
// to use any caracter from array use it in removeop like example
// if we have array (split return) have 100 5 30 60 333 we get 100 for example
// we need to make removeop(n[0]) and that reutrn 100;
// ok now to replace last value to negative in string you can just make
// var lastv=n[n.length-1];
// n[n.length-1] ='(-'+n[n.length-1])+')';
//var newstring=n.join('');
//n[n.length-1]=lastv;
//var oldstring=n.join('');
}
function removeop(stringop)
{
stringop = stringop.replace('+','');
stringop = stringop.replace('-','');
stringop = stringop.replace('*','');
stringop = stringop.replace('/','');
return stringop;
}
If you really need to add "()", then you can modify accordingly
<script>
function myConversion(){
var str = "100/5*30-60-333";
var p = str.lastIndexOf("+");
if(p>-1)
{
str = str.replaceAt(p,"-");
}
else
{
var n = str.lastIndexOf("-");
if(n>-1)
str = str.replaceAt(n,"+");
}
console.log(str);
}
String.prototype.replaceAt=function(index, replacement) {
return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}
</script>

Check if numbers are in sequence

I have a textbox that contains a max length of 4 and if the user enters the numbers in sequence then needs to throw an error.
Examples: Below are a few examples which need to block:
1234, 4567, 5678, etc
And it can accept 1233, 4568, etc
I'm expecting this condition in Jquery or JavaScript.
Any help would be appreciated
Code: I want to use the code in below format:
$.validator.addMethod('Pin', function (b) {
var a = true;
a = (/^([0-9] ?){4}$/i).test(b);
return a
}, '');
We can replace the condition which is in bold.
The simplest solution would be to use the following code
/**
* The sequential number would always be a subset to "0123456789".
* For instance, 1234, 4567, 2345, etc are all subset of "0123456789".
* To validate, this function uses 'indexOf' method present on String Object.
* you can read more about 'indexOf' at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
*/
$.validator.addMethod("Pin", function(b) {
var numbers = "0123456789";
//If reverse sequence is also needed to be checked
var numbersRev = "9876543210";
//Returns false, if the number is in sequence
return numbers.indexOf(String(b)) === -1 && numbersRev.indexOf(String(b)) === -1;
}, "");
The condition with the variable numbersRev is only needed if the reverse sequence validation is also required
You can simply split the pin into individual digits, and iterate through them to ensure that there is at least one part that is not in sequential order (i.e difference of +2 or more):
$.validator.addMethod("Pin", function(value, element) {
var digits = value.split(''),
invalid = true;
// Iterate through pairs of values
// As long as one comparison is not consecutive, the PIN is valid
for(var i = 0; i < digits.length - 1; i++) {
if (parseInt(digits[i]) - parseInt(digits[i+1]) > 1) {
invalid = false;
break;
}
}
return !invalid;
}, "");
If you want to also accommodate for cases of descending sequences, i.e. 9876, simply check for the absolute difference between one digit to another, i.e.:
Math.abs(parseInt(digits[i]) - parseInt(digits[i+1])) > 1
Proof-of-concept logic:
// Test values
var values = ['1234', '1235', '4321', '5321'];
for(var v = 0; v < values.length; v++) {
var value = values[v],
digits = value.split(''),
invalid = true;
for(var i = 0; i < digits.length - 1; i++) {
if (Math.abs(parseInt(digits[i]) - parseInt(digits[i+1])) > 1) {
invalid = false;
break;
}
}
console.log('PIN: ' + value + '. Valid? ' + !invalid);
}
You can do like this:
//with array
var numArray = [1234, 1243];
for (var i = 0; i < numArray.length; i++) {
checkIfSequential(numArray[i]);
}
//with string
var numberGiven = 1234;
checkIfSequential(numberGiven);
function checkIfSequential(num) {
var newNum = num + ''
newNum = newNum.split('');
console.log(num + ': ' + newNum.every((num, i) => i === newNum.length - 1 || num < newNum[i + 1]));
}
I get your point,
Why dont you just set the max length of the input field in the HTML itself and then bind a keyup event to the input box to trigger the validation ?
ex:
<input type="text" maxlength="4" onkeyup="validateMe()" id="key"/>
<script>
validateMe = function(){
if(document.getElementById("key").value == "1234"){
alert("yay! Key accepted!!");
}
};
</script>
In order to fulfill the requirements for max length of 4 digits.
We enumerate all possible sequential digits according to the OP constraints [1234, 2345, 3456, 4567, 5678, 6789], and then check them with the input arguments.
const sequentialDigits = (input) => {
const allSeqNumsArr = [1234, 2345, 3456, 4567, 5678, 6789];
return allSeqNumsArr.filter((num) => num === input).length > 0;
};
console.log(sequentialDigits(1234));
console.log(sequentialDigits(1235));
console.log(sequentialDigits(5321));

Clip off last digits from arrays

I have the following array
var arr = ['1234','23C','456','356778', '56']
I want to remove array elements which are less than 3 characters and greater than 4 characters. The final result should be as follows
arr = ['1234', '23C', '456']; //only 3 and 4 digits in the array.
Secondly, I want to do the following. if 'arr' has elements longer than 3 characters, I need to clip of by removing the last digit. The final 'data' array should look like this.
arr = ['123', '23C', '456'];
For the first part, you can just use filter to filter out numbers that aren't composed of 3 digits.
var arr = [1234, 234, 456, 356778, 56];
var result = arr.filter(function(num) {
return num < 1000 && num >= 100;
});
console.log(result);
For the second part, you can use map. Just convert the number to a string. If the length of it is greater than 3, take the substring composed of the first 3 elements of the string, then convert back to a number.
var data = [1234, 123, 4567, 3333];
var result = data.map(function(num) {
num = num.toString().substring(0, 3);
return parseInt(num);
});
console.log(result);
All You want is Array.filter and Array.map, and converting String to Number
var arr = [1234,234,456,356778, 56]
var newArr = arr.filter((num) => {
// convert number to string
var str = '' + num
// if length is 3 or 4 - return true (element will be in newArr)
return str.length === 3 && str.length === 4
})
and the second case
var newArr = arr.map((num) => {
var str = '' + num
// is str is longer than 3, cut it to length of 3
if(str.length > 3)
str = str.substring(0, 3)
// return str converted to number
return +str
})
function filterArray(arr,lowDigits,highDigits){
var newArr=[];
for(i=0;i<arr.length;i++){
val=arr[i];
length=val.length;
if(length>=lowDigits&&length<=highDigits){
if(length>lowDigits){
val=val.substring(0,lowDigits);
}
newArr.push(val);
}
}
return newArr;
}
var arr = ['1234','234','456','356778','56'];
arr=filterArray(arr,3,4);
console.log(arr);
To handle if a number is 3 or 4 digits, check if each number is in the range 100 <= num < 10000
let result = arr.filter(function(val) {
// is a 3 or 4 digit number
return 100 >= val && num < 10000;
});
To clip the four digits to 3 digits, we can divide all four digit numbers by 10 and convert them to an integer
let clippedResult = result.map(function(val) {
return val >= 1000 ? Math.floor(val / 10) : val
});
This solution converts the input array to a string of the form 1234,23C,456,356778,56, then finds the wanted elements using regexp.
var arr = ['1234','23C','456','356778', '56'];
console.log(String(arr).match(/\b\w{3}(?=\w?\b)/g));
In English:
Find all the substrings which start with a word boundary (\b, which will be after a comma, or the beginning of the string), then have three alphanumeric characters, and which looking ahead ((?=) may (?) have one additional character before the next word boundary (comma or end of string).
And yes, this will work with string elements, as long as the strings are composed of alphanumerics (in other words, things which won't break the word break (\b) logic.
let isValidElement = updated_ImportDetails.ImportData.filter(function (num) {
// is a 3 or 4 digit number
return num.length > 2 && num.length <4 ;
});
var result = isValidElement.map(function (num) {
num = num.substring(0, 3);
return num;
});
result = result.filter(function (elem, index, self) {
return index == self.indexOf(elem);
}) //removes duplicates from the array
This worked for me.

Replace every nth character from a string

I have this JavaScript:
var str = "abcdefoihewfojias".split('');
for (var i = 0; i < str.length; i++) {
var xp = str[i] = "|";
}
alert( str.join("") );
I aim to replace every fourth letter in the string abcdefoihewfojias with |, so it becomes abc|efo|....etc,but I do not have a clue how to do this.
You could just do it with a regex replace:
var str = "abcdefoihewfojias";
var result = str.replace(/(...)./g, "$1|");
console.log(result);
To support re-usability and the option to wrap this in an object/function let's parameterise it:
var str = "abcdefoihewfojias".split('');
var nth = 4; // the nth character you want to replace
var replaceWith = "|" // the character you want to replace the nth value
for (var i = nth-1; i < str.length-1; i+=nth) {
str[i] = replaceWith;
}
alert( str.join("") );
This might help you solve your problem
var str = "abcdefoihewfojias".split("");
for (var i = 3; i < str.length - 1; i+=4) {
str[i] = "|";
}
alert( str.join("") );
You go with for loop from the the first char that you want to replace (the 3 char) until the one digit before the end and replace every 4 places.
If the for loop will go from the str.length and not to str.length-1 sometimes at the last char will be |.
.map one-liner
You can use this one-liner:
var str = "abcdefoihewfojias";
str.split('').map(function(l,i) {
return (i + 1) % 4 ? l : '|';
}).join('');
% returns the remainder. So:
# | Result (# + 1) % 4
---|-------
0 | 1
1 | 2
2 | 3
4 | 0 // Bingo!
ES6 alternative
With ES6, you can do:
[...str].map((l,i) => (i + 1) % 4 ? l : '|')
Simple just use modulus
https://jsfiddle.net/ctfsorwg/
var str = "abcdefoihewfojias";
var outputStr = str.split("");
for (var i = 0; i < outputStr.length; i++) {
if(!((i+1)%4))outputStr[i] = '|';
}
alert( "Before: " + str + "\nAfter: " + outputStr.join(""));
While there are several answers already, I thought I'd offer a slightly alternative approach, using Array.prototype.map(), wrapped in a function that can be adapted by the user (to update the value of n in the nth character, and change the replacement character used):
// defining the named function, with an 'opts' argument:
function replaceNthWith(opts) {
// setting the default options:
var defaults = {
// defining the nth character, in this case
// every fourth:
'nth': 4,
// defining the character to replace that
// nth character with:
'char': '|'
};
// Note that there's no default string argument,
// so that one argument must be provided in the
// opts object.
// iterating over each property in the
// opts Object:
for (var property in opts) {
// if the current property is a property of
// this Object, not inherited from the Object
// prototype:
if (opts.hasOwnProperty(property)) {
// we set that property of the defaults
// Object to be equal to that property
// as set in the opts Object:
defaults[property] = opts[property];
}
}
// if there is a defaults.string property
// (inherited from the opts.string property)
// then we go ahead; otherwise nothing happens
// note: this property must be set for the
// function to do anything useful:
if (defaults.string) {
// here we split the string supplied from the user,
// via opts.string, in defaults.string to form an
// Array of characters; we iterate over that Array
// with Array.prototype.map(), which process one
// Array and returns a new Array according to the
// anonymous function supplied:
return haystack = defaults.string.split('').map(function(character, index) {
// here, when the index of the current letter in the
// Array formed by Array.prototype.split() plus 1
// (JavaScript is zero-based) divided by the number
// held in defaults.nth is equal to zero - ensuring
// that the current letter is the 'nth' index we return
// the defaults.char character; otherwise we return
// the original character from the Array over which
// we're iterating:
return (index + 1) % parseInt(defaults.nth) === 0 ? defaults.char : character;
// here we join the Array back into a String, using
// Array.prototype.join() with an empty string:
}).join('');
}
}
// 'snippet.log()' is used only in this demonstration, in real life use
// 'console.log()', or print to screen or display in whatever other
// method you prefer:
snippet.log( replaceNthWith({ 'string': "abcdefoihewfojias" }) );
function replaceNthWith(opts) {
var defaults = {
'nth': 4,
'char': '|'
};
for (var property in opts) {
if (opts.hasOwnProperty(property)) {
defaults[property] = opts[property];
}
}
if (defaults.string) {
return haystack = defaults.string.split('').map(function(character, index) {
return (index + 1) % parseInt(defaults.nth) === 0 ? defaults.char : character;
}).join('');
}
}
// 'snippet.log()' is used only in this demonstration, in real life use
// 'console.log()', or print to screen or display in whatever other
// method you prefer.
// calling the function, passing in the supplied 'string'
// property value:
snippet.log( replaceNthWith({
'string': "abcdefoihewfojias"
}) );
// outputs: abc|efo|hew|oji|s
// calling the function with the same string, but to replace
// every second character ( 'nth' : 2 ):
snippet.log( replaceNthWith({
'string': "abcdefoihewfojias",
'nth': 2
}) );
// outputs: a|c|e|o|h|w|o|i|s
// passing in the same string once again, working on every
// third character, and replacing with a caret ('^'):
snippet.log( replaceNthWith({
'string': "abcdefoihewfojias",
'nth': 3,
'char' : '^'
}) );
// outputs: ab^de^oi^ew^oj^as
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
References:
Array.prototype.map().
Array.prototype.join().
for...in loop.
JavaScript Remainder (%) operator.
Object.prototype.hasOwnProperty().
String.prototype.split().
function replaceWith(word,nth, replaceWithCh) {
//match nth position globally
//'\S' is for non-whitespace
let regex = new RegExp("(\\S{" + (nth - 1) + "})\\S", "g");
// '$1' means single group
// after each group position replaceWithCharecter
let _word = word.replace(regex, "$1" + replaceWithCh);
return _word;
}
const str = "abcdefoihewfojias";
const result = replaceWith(str, 3, "X");
console.log(result);

How to determine where's the place of number in a string

How to determine after which comma is the place of the number 13 in a string with commas(,) with JS?
For example:
string - testtest,teststestatestb,testj
The letter "s" is the 13-th letter and it's after the first comma.
I'm not sure if I understand your Question. But here is a possible solution:
function count_commas_to_position(string,position) {
return string.substring(0,position).replace(/[^,]/g,'').length
}
// if you don't want to count commas on `position`
function count_commas_to_position(string,position) {
return string.substring(0,position-1).replace(/[^,]/g,'').length
}
var string = "testtest,teststestatestb,testj"
var comma_count = count_commas_to_position(string,13);
You need to split string in array with ',' and then check for each string length using loop in correspond to array length.
like
var str="testtest,teststestatestb,testj";
var a1 = new Array();
a1=str.split(",");
for(var i=0;i < a1.length ; i++ )
{
if(a1[i].length > 13)
{
//get 13th index of the word.
}
}
Try
a.indexOf('s',a.indexOf(','))
write a method
function abc(){
var a = "esttestte,ststestatestbtestj"
var c = a.indexOf(',')
if (c==-1)
alert("',' is not present ")
else{
var b =a.indexOf('s',c)
if (b==-1)
alert("'s' is not present after ','")
else
alert("position of 's' after ',' is "+(b+1) )
}
}

Categories

Resources