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');
Related
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'));
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);
The code below doesn't work why?
function titleCase(str){
var newStr = str.split(" "); //split string turn it into seperated words[]
var resutl;
for(vari=0; i < newStr.length; i++){ //iterate all words
var result = newStr[i].charAt(0).toUpperCase +
// find first letter and turn it into capital
newStr[i].subString(1).toLowerCase();
}
return result.join(" ");
}
result in your code is a string, not an array. you cannot join a string.
each iteration of the loop you are replacing the variable result with a new word. you need to initialize a result array [] and push each result onto the array, then join the array after the loop has completed.
The result needs to be an array and also you have some typos in your code, e.g. missing ()
function titleCase(str) {
var newStr = str.split(" ");
var result = [];
for (var i = 0; i < newStr.length; i++) {
result.push(newStr[i].charAt(0).toUpperCase() + newStr[i].substring(1).toLowerCase());
}
return result.join(' ');
}
var str = 'hELLO wORLD';
document.write(titleCase(str));
Try using regular expression
var data = "The mission is to turn each word's first letter into capital";
data = data.replace(/ (.)/g,function(w){return w.toUpperCase()});
drawback :this will not capitalize the first character.
Explode the string on spaces and iterate it with the function below:
function ucfirst(str) {
str += ''; // make sure str is really a string
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
}
You may try this :
function titleCase(str){
var newStr = str.split(" ");
var result = [];
for(var i=0; i < newStr.length; i++){
result.push(newStr[i].charAt(0).toUpperCase() +
newStr[i].substring(1).toLowerCase());
}
return result.join(' ');
}
Another Approach:
function titleCase(str){
var words = str.split(" ");
return words.map(function(word){
return word.charAt(0).toUpperCase() + word.substring(1).toLowerCase();
}).join(" ");
}
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
I have a strings that can look like this:
left 10 top 50
How can i extract the numbers, while the numbers can range from 0 to 100 and words can be left/right top/bottom? Thanks
Try match()
var text = "top 50 right 100 left 33";
var arr = text.match(/[0-9]{1,3}/g);
console.log(arr); //Returns an array with "50", "100", "33"
You can also use [\d+] (digits) instead of [0-9]
Place this string in a var, if you know every number will be seperated by a space you can easely do the following:
var string = "top 50 left 100";
// split at the empty space
string.split(" ");
var numbers = new Array();
// run through the array
for(var i = 0; i < string.length; i++){
// check if the string is a number
if(parseInt(string[i], 10)){
// add the number to the results
numbers.push(string[i]);
}
}
Now you can wrap the whole bit in a function to run it at any time you want:
function extractNumbers(string){
var temp = string.split(" ");
var numbers = new Array();
for(var i = 0; i < temp.length; i++){
if(parseInt(temp[i], 10)){
numbers.push(temp[i]);
}
}
return numbers;
}
var myNumbers = extractNumbers("top 50 left 100");
Update
After reading #AmirPopovich s answer, it helped me to improve it a bit more:
if(!isNaN(Number(string[i]))){
numbers.push(Number(string[i]));
}
This will return any type of number, not just Integers. Then you could technically extend the string prototype to extract numbers from any string:
String.prototype.extractNumbers = function(){ /*The rest of the function body here, replacing the keyword 'string' with 'this' */ };
Now you can do var result = "top 50 right 100".extractNumbers();
Split and extract the 2nd and 4th tokens:
var arr = "left 10 top 50".split(" ");
var a = +arr[1];
var b = +arr[3];
var str = 'left 10 top 50';
var splitted = str.split(' ');
var arr = [];
for(var i = 0 ; i < splitted.length ; i++)
{
var num = Number(splitted[i]);
if(!isNaN(num) && num >= 0 && num <= 100){
arr.push(num);
}
}
console.log(arr);
JSFIDDLE
If you want it dynamically by different keywords try something like this:
var testString = "left 10 top 50";
var result = getNumber("top", testString);
function getNumber(keyword, testString) {
var tmpString = testString;
var tmpKeyword = keyword;
tmpString = tmpString.split(tmpKeyword + " ");
tmpString = tmpString[1].split(' ')[0];
return tmpString;
}
var myArray = "left 10 top 50".split(" ");
var numbers;
for ( var index = 0; index < myArray.length; index++ ) {
if ( !isNaN(myArray[index]))
numbers= myArray[index]
}
find working example on the link below
http://jsfiddle.net/shouvik1990/cnrbv485/