How to reverse value in javascript - javascript

hello I have values like this
1-10
2-3
901-321
I want to get the reverse values for example like this
10-1
3-2
321-901
I have tried this
var str = "1-18";
var newString = "";
for (var i = str.length - 1; i >= 0; i--) {
newString += str[i];
}
return newString;
But it gives me 81-1

Instead, use String.split(), Arrary.reverse() and Arrary.join():
var str = '901-321';
var strArray = str.split('-'); // ['901', '321']
var strArrayReversed = strArray.reverse(); // ['321', '901']
var result = strArrayReversed.join('-'); // '321-901'
console.log('result = ', result);
// You can do all these steps above in one go as:
var result2 = str.split('-')
.reverse()
.join('-');
console.log('result2 = ', result2);
MDN Docs:
String.prototype.split()
Array.prototype.reverse()
Array.prototype.join()

Can split on the - to create array , reverse the array and join it back into string
var str = "1-18",
newStr = str.split('-').reverse().join('-');
console.log(newStr)

a = "12-5"
console.log(a.split('-').reverse().join('-'))

You can use the split method to divide the string in two, and then use the second part before the first, like this:
var str = "1-18";
var l = str.split("-");
return l[1] + "-" + l[0];

You could replace the string by swapping the values.
var string = '901-321';
console.log(string.replace(/(.+)-(.+)/, '$2-$1'));

Related

Splitting string with comma, issue with money

I have string like below which i'd like to split by comma's. But there's an issue with the money which is also has comma in it.
What i like to achieve; if there's a number after comma do not seperate from that one. I'd like to do the job with javascript.
025056-03110,245056030,1,Standart Discount,Standart Discount,15,940.00USD,29/11/2017,1,
What i've tried so far with thousand combinations;
[^\,!\?]+
What i expect as a result;
025056-03110
245056030
1
Standart Discount
Standart Discount
*15,940.00USD*
29/11/2017
1
The solution here is to use .match() with this regex /(\d+,\d{3}[.]\d+\w+)|(\d+[\-][\d\w]+)|([\/\d\s\w]+)/g, it will split all the elements and skip the numbers that have a comma.
This is how should be your code:
var str = "025056-03110,245056030,1,Standart Discount,Standart Discount,15,940.00USD,29/11/2017,1";
var matches = str.match(/(\d+,\d{3}[.]\d+\w+)|(\d+[\-][\d\w]+)|([\/\d\s\w]+)/g);
Demo:
var str = "025056-03110,245056030,1,Standart Discount,Standart Discount,15,940.00USD,29/11/2017,1";
var matches = str.match(/(\d+,\d{3}[.]\d+\w+)|(\d+[\-][\d\w]+)|([\/\d\s\w]+)/g);
console.log(matches);
let str = '025056-03110,245056030,1,Standart Discount,Standart Discount,15,940.00USD,29/11/2017,1,';
let price = str.match(/[A-Za-z],(\d+,?\d{1,3}\.\d{2}\w{3})/)[1];
let temp = price.replace(',', '|');
console.log(
str.replace(price, temp)
.split(',')
.map(v => v.replace('|', ','))
.filter(v => v)
);
Maybe you could do it like this:
(?:\d+,(?=\d+\.).+?(?=,)|[\w-\/.\s]+)
var pattern = /(?:\d+,(?=\d+\.).+?(?=,)|[\w-\/.\s]+)/g;
var str = "025056-03110,245056030,1,Standart Discount,Standart Discount,15,940.00USD,29/11/2017,1,";
var matches = str.match(pattern);
for (var i = 0; i < matches.length; i++) {
if (matches[i].indexOf('USD') !== -1) {
matches[i] = "*" + matches[i] + "*";
}
}
console.log(matches.join('\n'));
Rather match with alternatives: \*[^*]*\*|[^\s,][^,]*
var s = '025056-03110,245056030,1,Standart Discount,Standart Discount,*15,940.00USD*,29/11/2017,1,';
var res = s.match(/\*[^*]*\*|[^\s,][^,]*/g);
console.log(res);

JS check if value exist in space seperated values

I have a space separated values 80,3537,3718,3721, 1519, 2344 and i want to check if the second value matches any of the space separated values
For example if the second value equals any of the following 3 then the output should be pass
80,3537,3718,3721
1519
2344
The following value should fail because it does not match any of the space seperated values
2000
I want to achieve this in plain javascript, how can this be done.
UPDATE:
This is what i tried so far to check if result2 exist in result1 space separated values
var result1 = '80,3537,3718,3721, 1519, 2344'
var result2 = '1519'
if (result1.match(new RegExp("(?:^|,)" + result2 + "(?:,|$)"))) {
console.log(true);
}
Your regex needs a slight modification in order for it to cover all the possible cases.
var result1 = "80,3537,3718,3721, 1519, 2344";
var result2 = "1519";
if (new RegExp("(^|(,\\s))" + result2 + "(,|$)").test(result1)) {
console.log(true);
}
I recommend creating a little helper function. I don't see any code to get more specific, but this should work fine.
function checkVal(str, val) {
const arr = str.split(' ');
return arr.includes(val);
}
//For Example...
let exStr = '132,340,23 32 345 1,223',
exVal = '345';
alert(checkVal(exStr, exVal));
(Edit)
Using your variables, it would look like this. I added a space and comma to the split to match the ', ' you have between each value in your example.
var result1 = '80,3537,3718,3721, 1519, 2344';
var result2 = '1519';
var test = result1.split(', ').includes(result2);
console.log(test);
You can split the space separated string first.
var secondNumber = whatever;
var string = "80,3537,3718,3721, 1519, 2344";
var ans = string.split(" ");
for (int i = 0; i < ans.length; i++) {
num = ans[i];
num.replace(/,/g , "");
num = parseInt(num, 10);
}
if (ans.indexOf(secondNumber) > -1 ) {
return true;
}
return false;
var str = '80,3537,3718,3721, 1519, 2344';
var arr = str.split(' ');
for(var i=0;i<arr.length;i++){
arr[i] = arr[i].trim().replace(/,\s*$/, "");
}
console.log((arr.indexOf('1519') === 1)?'true':'false');

How can I get this result in RegEx using Javascript

If my entry is "001.1-2016", I want "001.2-2016"
If my entry is "001.8-2015", I want "001.9-2016"
If my entry is "001.12-2014", I want "001.13-2016"
If my entry is "001.123-2016", I want "001.124-2016"
I tried a regex like this:
([0-9]{3}\.)(.*)(\-[0-9]{4})
but this get all, I want only the middle.
Your regex (\[0-9\]{3}\.)(.*)(\-\[0-9\]{4}) works fine, you just need to get the second captured group result.
var arr = ["001.1-2016", "001.8-2015", "001.12-2014", "001.123-2016"];
var regex = /([0-9]{3}\.)(.*)(\-[0-9]{4})/;
arr.forEach(function(str) {
document.body.innerHTML += str.match(regex)[2] + '<br />';
});
You can use String#split and parseInt.
var value = "001.12-2014";
var num = parseInt(value.split('.')[1], 10);
var value = "001.12-2014";
var num = parseInt(value.split('.')[1], 10);
document.body.innerHTML = num;
Using Regex
var value = "001.12-2014";
var num = value.match(/.*?\.(\d+)/)[1];
var value = "001.12-2014";
var num = (value.match(/.*?\.(\d+)/) || [])[1];
document.body.innerHTML = num;
I need just add +1 in this number, eg. "001.12-2014" >>> "001.13-2014" or "001.123-2014" >>> "001.124-2014"
var arr = ["001.1-2016", "001.8-2015", "001.12-2014", "001.123-2016"];
arr = arr.map(e => e.replace(/\.(\d+)/, ($0, $1) => '.' + (1 + +$1)));
document.body.innerHTML = arr;
To increment the number by 1 you can use String#replace
document.getElementById('input').addEventListener('keyup', function() {
var value = this.value;
value = value.replace(/\.(\d+)/, function($0, $1) {
return '.' + (1 + +($1 || 0));
});
document.getElementById('output').innerHTML = value;
}, false);
<input type="text" id="input" />
<pre id="output"></pre>
The regex pattern could be
/[0-9]+\.([0-9]+)\-[0-9]+/g
if you do not concern the number format before . and after -
You can test it on here.
Try to use split method .The split() method splits a String object into an array of strings by separating the string into substrings.
<script>
function myFunction() {
var str = "001.12-2014";
var res = new Array();
res=str.split(".");
var finalres=res[1].split("-",1);
document.getElementById("demo").innerHTML = finalres;
}
</script>
Output:
this matches all 4 (find the decimal and take one or more digits that follow):
/\.(\d+)/g
# https://regex101.com/r/qG2mX7/4

JavaScript get character in sting after [ and before ]

I have some strings like:
str1 = "Point[A,B]"
str2 = "Segment[A,B]"
str3 = "Circle[C,D]"
str4 = "Point[Q,L]"
Now I want to have function that gives me character after "[" and the character before "]". How could I make something like that ?
try this one...
var str = "Point[A,B]";
var start_pos = str.indexOf('[') + 1;
var end_pos = str.indexOf(']',start_pos);
var text_to_get = str.substring(start_pos,end_pos)
alert(text_to_get);
You'd need regex to do that
var matches = /\[(.*?)\]/.exec(str1);
alert(matches[1]);
You can use match() to extract the characters:
str.match(/\[(.*)\]/)[1]
A safer way would be:
var matches = str.match(/\[(.*)\]/);
if(matches) {
var chars = matches[1];
}
Here's an approach which avoids regex.
var str = "Point[A,B]";
var afterOpenBracket = str.split("[")[1]; // returns "A,B]"
var bracketContents = afterOpenBracket.split("]")[0]; // returns "A,B"
There, pretty simple! bracketContents now contains the entirety of the text between the first set of brackets.
We can stop here, but I'll go a step further anyway and split up the parameters.
var parameters = bracketContents.split(","); // returns ["A", "B"]
Or in case u have more [A,C,D,B] and don't want to use regex:
var str1 = "Point[A,C,D,B]";
function extract(str1){
var a = str1.charAt(str1.indexOf('[')+1);
var b = str1.charAt(str1.indexOf(']')-1);
return [a, b];
//or
//a.concat(b); //to get a string with that values
}
console.log(extract(str1));

Splitting in string in JavaScript

How to split a string in JavaScript with the "," as seperator?
var splitString = yourstring.split(',');
See split
var str = "test,test1,test2";
var arrStr = str.split(',');
var arrLength = arrStr.length; //returns 3
Use split to split your string:
"foo,bar,baz".split(",") // returns ["foo","bar","baz"]
var expression = "h,e,l,l,o";
var tokens = expression.split("\,");
alert(tokens[0]);// will return h

Categories