Append number to a comma separated list - javascript

the list looks like:
3434,346,1,6,46
How can I append a number to it with javascript, but only if it doesn't already exist in it?

Assuming your initial value is a string (you didn't say).
var listOfNumbers = '3434,346,1,6,46', add = 34332;
var numbers = listOfNumbers.split(',');
if(numbers.indexOf(add)!=-1) {
numbers.push(add);
}
listOfNumbers = numbers.join(',');
Basically i convert the string into an array, check the existence of the value using indexOf(), adding only if it doesn't exist.
I then convert the value back to a string using join.

If that is a string, you can use the .split() and .join() functions, as well as .push():
var data = '3434,346,1,6,46';
var arr = data.split(',');
var add = newInt;
arr.push(newInt);
data = arr.join(',');
If that is already an array, you can just use .push():
var data = [3434,346,1,6,46];
var add = newInt;
data.push(add);
UPDATE: Didn't read the last line to check for duplicates, the best approach I can think of is a loop:
var data = [3434,346,1,6,46];
var add = newInt;
var exists = false;
for (var i = 0; i < input.length; i++) {
if (data[i] == add) {
exists = true;
break;
}
}
if (!exists) {
data.push(add);
// then you would join if you wanted a string
}

You can also use a regular expression:
function appendConditional(s, n) {
var re = new RegExp('(^|\\b)' + n + '(\\b|$)');
if (!re.test(s)) {
return s + (s.length? ',' : '') + n;
}
return s;
}
var nums = '3434,346,1,6,46'
alert( appendConditional(nums, '12') ); // '3434,346,1,6,46,12'
alert( appendConditional(nums, '6') ); // '3434,346,1,6,46'
Oh, since some really like ternary operators and obfustically short code:
function appendConditional(s, n) {
var re = new RegExp('(^|\\b)' + n + '(\\b|$)');
return s + (re.test(s)? '' : (''+s? ',':'') + n );
}
No jQuery, "shims" or cross-browser issues. :-)

Related

Remove a value in a string with a wildcard using Javascript

I'm trying to return a comma separated string without the items that end in 'non'.
Source:
id = '2345,45678,3333non,489,2333non';
Expected Result:
id = '2345,45678,489';
I'm using code that I found here:
remove value from comma separated values string
var removeValue = function(list, value, separator) {
separator = separator || ",";
var values = list.split(separator);
for (var i = 0; i < values.length; i++) {
if (values[i] == value) {
values.splice(i, 1);
return values.join(separator);
}
}
return list;
}
Is there a way to make the line (values[i] == value) use a wildcard?
Use /[^,]*non,|,[^,]*non/g:
id = '2345,45678,3333non,489,2333non';
console.log(
id.replace(/[^,]*non,|,[^,]*non/g, '')
)
As a function:
id = '2345,45678,3333non,489,2333non';
removeItem = function(s, ends) {
pat = new RegExp(`[^,]*${ends},|,[^,]*${ends}`, 'g')
return s.replace(pat, '')
}
console.log(removeItem(id, 'non'))
You can also get that result without using regex like this:
var id = '2345,45678,3333non,489,2333non';
var resArray = id.split(',').filter((item) => item.indexOf('non') === -1);
var resString = resArray.toString();
console.log(resString);
If you do not want to use arrow funtion:
var id = '2345,45678,3333non,489,2333non';
var resArray = id.split(',').filter(function(item) {
return item.indexOf('non') === -1;
});
var resString = resArray.toString();
console.log(resString);
You don't need regex for this. Just split on , and filter the array for all elements that don't end in non.
var id = '2345,45678,3333non,489,2333non'
console.log(id.split(',').filter(x => !x.endsWith('non')).join(','))
Thanks to Nope for pointing out that endsWith() will not work in IE. To get around this issue, see Mozilla's Polyfill for endsWith or JavaScript endsWith is not working in IEv10.

How to parse value in JavaScript?

Sample string:
(13.910074099911057%2C+100.37796020507812)%2C(13.840746785080066%2C+100.27908325195312)%2C(13.712703652698178%2C+100.33126831054688)%2C(13.7620619168356%2C+100.50979614257812)
Correct format:
13.910074099911057, 100.37796020507812 13.840746785080066, 100.27908325195312 13.712703652698178, 100.33126831054688 13.7620619168356, 100.50979614257812
Sample code:
var locate = window.location
document.GetPerimeter.Perimeter.value = locate
var text = document.GetPerimeter.Perimeter.value
function CopyPerimeter(str) {
theleft = str.indexOf("=") + 1;
theright = str.lastIndexOf("&");
return (str.substring(theleft, theright));
}
var ShowPerimeter = CopyPerimeter(text)
document.GetPerimeter.Perimeter.value = ShowPerimeter
function decode() {
var obj = document.getElementById('Perimeter');
var encoded = obj.value;
obj.value = decodeURIComponent(encoded.replace(/\+/g, ""));
}
decode();
This is the script which parses your JAVASCRIPT String to the desired one:
var str = "(13.910074099911057%2C+100.37796020507812)%2C(13.840746785080066%2C+100.27908325195312)%2C(13.712703652698178%2C+100.33126831054688)%2C(13.7620619168356%2C+100.50979614257812)";
var strParsed = "";
var percentCame = 0;
for (var i=0; i < str.length; i++) {
if( (str[i]!="(") && (str[i]!=")") ){
if( (str[i]=="%") ){
percentCame = 1;
}
if(percentCame==1){
i += 4;
strParsed = strParsed + "," + str[i];
percentCame = 0;
}
else{
strParsed = strParsed + str[i];
}
}
}
You can use Regular Expressions to parse text in Javascript. Just use the myString.match('myRegEx') function and it will return an array with parsed values. Mind that the values are still in text format so they need to be cast into floats if you want to use them as such.
This regular expression might do the trick: /[-+]?\d+\.?\d*[^)C%]/g
If you need to modify the regular expressions to match other values, try using a online helper as the ones below:
http://www.regexr.com/
https://regex101.com/#javascript
I hope I understood your question correct.

How to insert default value in the comma separated strings?

I have group of comma separated strings and if any string is not a numeric value, I need to insert "(1)".
"stack(2),flow,over(4),temp(7)" Here insert default value to flow(1)
"stack(2),flow(3),over(4),temp" Here insert default value to temp(1)
"stack,flow(3),over,temp" Here insert default value to stack(1),over(1),temp(1)
I have validation code to validate and insert default values where needed. Please help me how to insert a default value within parentheses.
javascript function :
var case1 = "stack(2),flow(2),over(4),temp(7)"; // - true
var case2 = "stack(2),flow(3),over(4),temp(k)"; // - false
var case3 = "stack(2),flow(2),over(4),temp(0"; // - false
var case4 = "stack(2),flow(2),over(,temp)"; // - false
var case5 = "stack(2),flow(2),over(4)temp(8)"; // - false
var case6 = "stack(1),flow(7),over,temp"; // - true
var case7 = "stack(1),flow(7),OVER,Temp"; // - true
var case8 = "stack(1),flow(7),over_r,temp_t"; // - true
function testCases(str)
{
var pattern = /^[a-z]+(?:\(\d+\))?(?:,[a-z]+(?:\(\d+\))?)*$/
return pattern.test(str);
}
The above function works for validation in jsfiddle
tl;dr
Use String.prototype.split and String.prototype.join to process each part of your string.
Details
If you want to apply custom fixes to your string, you need to split it in several parts and then process them. Once the job is done, concat all the parts together.
Implementation
Using Array.prototype.map (Warning: not compatible with IE 8 and below):
Demo on JSFiddle.
function testCases(str) {
return str.split(',').map(function(s) {
if (s.match(/^[a-z]+\(\d+\)$/i)) {
// string is valid
return s;
} else {
// you can do processing here based on the failure reason
return s + '(1)';
}
}).join(',');
}
Using a for loop (IE8-compatible):
function testCases(str) {
var parts = str.split(',');
var i = parts.length;
while (i--) {
var s = parts[i];
if (!s.match(/^[a-z]+\(\d+\)$/i)) {
// string is invalid
// you can do processing here based on the failure reason.
parts[i] = s + '(1)';
}
}
return parts.join(',');
}
Unfortunately, JavaScript doesn't have lookbehinds - they'd be very useful here. Instead, we have to cheat:
str = str.replace(/([^)])(,|$)/g,"$1(1)$2");
What this does is capture whatever character comes before the comma or end of string, provided it is not a close-parenthesis. It then inserts the (1) default value in that position.
var add_default = function(str, def) {
str = str.split(',');
for(var i = 0; i < str.length; ++i) {
if(!/\(\d+\)$/.test(str[i]))
str[i] += "(" + def + ")";
}
return str.join(',');
};
http://jsfiddle.net/BhVx3/3/
Here is a possible solution :
function fix(input) {
var r = /^(.*?)(?:\((\d*)\)?|\)?)$/,
input = input.split(','),
output = [],
item;
while (item = input.shift()) {
item = item.match(r);
item = item[1] + '(' + (item[2] || 1) + ')';
output.push(item);
}
return output.join();
}
var s = 'stack(2),over(4),flow,hello(0,kitty2)';
s = fix(s); // "stack(2),over(4),flow(1),hello(0),kitty2(1)"

How to get parameter value inside a string?

Here's a thing i've been trying to resolve...
We've got some data from an ajax call and the result data is between other stuff a huge string with key:value data. For example:
"2R=OK|2M=2 row(s) found|V1=1,2|"
Is it posible for js to do something like:
var value = someFunction(str, param);
so if i search for "V1" parameter it will return "1,2"
I got this running on Sql server no sweat, but i'm struggling with js to parse the string.
So far i'm able to do this by a VERY rudimentary for loop like this:
var str = "2R=OK|2M=2 row(s) found|V1=1,2|";
var param = "V1";
var arr = str.split("|");
var i = 0;
var value = "";
for(i = 0; i<arr.length; ++i){
if( arr[i].indexOf(param)>-1 ){
value = arr[i].split("=")[1];
}
}
console.log(value);
if i put that into a function it works, but i wonder if there's a more efficient way to do it, maybe some regex? but i suck at it. Hopefully somebody may shine a light on this for me?
Thanks!
This seems to work for your specific use-case:
function getValueByKey(haystack, needle) {
if (!haystack || !needle) {
return false;
}
else {
var re = new RegExp(needle + '=(.+)');
return haystack.match(re)[1];
}
}
var str = "2R=OK|2M=2 row(s) found|V1=1,2|",
test = getValueByKey(str, 'V1');
console.log(test);
JS Fiddle demo.
And, to include the separator in your search (in order to prevent somethingElseV1 matching for V1):
function getValueByKey(haystack, needle, separator) {
if (!haystack || !needle) {
return false;
}
else {
var re = new RegExp('\\' + separator + needle + '=(.+)\\' + separator);
return haystack.match(re)[1];
}
}
var str = "2R=OK|2M=2 row(s) found|V1=1,2|",
test = getValueByKey(str, 'V1', '|');
console.log(test);
JS Fiddle demo.
Note that this approach does require the use of the new RegExp() constructor (rather than creating a regex-literal using /.../) in order to pass variables into the regular expression.
Similarly, because we're using a string to create the regular expression within the constructor, we need to double-escape characters that require escaping (escaping first within the string and then escaping within in the created RegExp).
References:
RegExp.
String.match().
This should work for you and it's delimiters are configurable (if you wish to parse a similar string with different delimiters, you can just pass in the delimiters as arguments):
var parseKeyValue = (function(){
return function(str, search, keyDelim, valueDelim){
keyDelim = quote(keyDelim || '|');
valueDelim = quote(valueDelim || '=');
var regexp = new RegExp('(?:^|' + keyDelim + ')' + quote(search) + valueDelim + '(.*?)(?:' + keyDelim + '|$)');
var result = regexp.exec(str);
if(result && result.length > 1)
return result[1];
};
function quote(str){
return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
}
})();
Quote function borrowed form this answer
Usage examples:
var str = "2R=OK|2M=2 row(s) found|V1=1,2|";
var param = "V1";
parseKeyValue(str, param); // "1,2"
var str = "2R=OK&2M=2 row(s) found&V1=1,2";
var param = "2R";
parseKeyValue(str, param, '&'); // "OK"
var str =
"2R=>OK\n\
2M->2 row(s) found\n\
V1->1,2";
var param = "2M";
parseKeyValue(str, param, '\n', '->'); // "2 row(s) found"
Here is another approach:
HTML:
<div id="2R"></div>
<div id="2M"></div>
<div id="V1"></div>
Javascript:
function createDictionary(input) {
var splittedInput = input.split(/[=|]/),
kvpCount = Math.floor(splittedInput.length / 2),
i, key, value,
dictionary = {};
for (i = 0; i < kvpCount; i += 1) {
key = splittedInput[i * 2];
value = splittedInput[i * 2 + 1];
dictionary[key] = value;
}
return dictionary;
}
var input = "2R=OK|2M=2 row(s) found|V1=1,2|",
dictionary = createDictionary(input),
div2R = document.getElementById("2R"),
div2M = document.getElementById("2M"),
divV1 = document.getElementById("V1");
div2R.innerHTML = dictionary["2R"];
div2M.innerHTML = dictionary["2M"];
divV1.innerHTML = dictionary["V1"];
Result:
OK
2 row(s) found
1,2

jQuery removing values from a comma separate list

Given an input like:
<input type="test" value="3,4,9" />
What's the best way to remove a value like 9, 4 or 3, without having issues with the commas, I don't want this ending up:
value="3,4,"
value="3,,9"
value=",4,9"
Is there a clean way to get this done in JavaScript/jQuery?
You could split your value into an array, then filter out values you do not want.
$("input[type='test']").val().split(",") // ["3","4","9"]
.filter(function(v){return !isNaN(parseInt(v))}) // filter out anything which is not 0 or more
Here is a less terse version which filters out anything which is not numeric
var array = $("input[type='test']").val().split(",");
// If you are dealing with numeric values then you will want
// to cast the string as a number
var numbers = array.map(function(v){ return parseInt(v)});
// Remove anything which is not a number
var filtered = numbers.filter(function(v){ return !isNaN(v)});
// If you want to rejoin your values
var joined = filtered.join(",");
Finally change the value on the input
$("input[type='test']").val(joined);
Similar to PHP implode/explode functions
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
var explode = value.split(',');
explode.remove(1);
var implode = explode.join(',');
Documentation:
fce: Split
fce: Join
fce: Array.remove
No jQuery required :P
<script type="text/javascript">
//var subject = '3,4,9';
//var subject = '3,,9';
var subject = ',,4,9';
var clean = Array();
var i = 0;
subject = subject.split(',');
for (var a in subject)
{
if(subject[a].length)
{
clean[i] = subject[a];
i++;
}
}
document.write(clean.join(','));
</script>
You may also use pure javascript. Let say you want to take off only "4":
value = value.replace(/4,?/, '')
or "3" and "9":
value = value.replace(/([39],?)+/, '')
I think this function will work for what you are trying to do: http://www.w3schools.com/jsref/jsref_split.asp
string.split(separator, limit)
use
array = string.split(separator);
to break a string into an array. then use this to join after manipulations.
string = array.join(separator);
var ary = value.split(',');
ary.splice(indexOfItemToRemove,1)
var result = ary.join(',');
This is discussed in another post:
remove value from comma separated values string
var removeValue = function(list, value, separator) {
separator = separator || ",";
var values = list.split(",");
for(var i = 0 ; i < values.length ; i++) {
if(values[i] == value) {
values.splice(i, 1);
return values.join(",");
}
}
return list;
}
You can use this function:
function removeComma(x) {
var str = '';
var subs = '';
for(i=1; i<=x.length; i++) {
subs = x.substring(i-1, i).trim();
if(subs !== ',') {
str = str+subs;
}
}
return str;
}

Categories

Resources