This code generates a comma separated string to provide a list of ids to the query string of another page, but there is an extra comma at the end of the string. How can I remove or avoid that extra comma?
<script type="text/javascript">
$(document).ready(function() {
$('td.title_listing :checkbox').change(function() {
$('#cbSelectAll').attr('checked', false);
});
});
function CotactSelected() {
var n = $("td.title_listing input:checked");
alert(n.length);
var s = "";
n.each(function() {
s += $(this).val() + ",";
});
window.location = "/D_ContactSeller.aspx?property=" + s;
alert(s);
}
</script>
Use Array.join
var s = "";
n.each(function() {
s += $(this).val() + ",";
});
becomes:
var a = [];
n.each(function() {
a.push($(this).val());
});
var s = a.join(', ');
s = s.substring(0, s.length - 1);
You can use the String.prototype.slice method with a negative endSlice argument:
n = n.slice(0, -1); // last char removed, "abc".slice(0, -1) == "ab"
Or you can use the $.map method to build your comma separated string:
var s = n.map(function(){
return $(this).val();
}).get().join();
alert(s);
Instead of removing it, you can simply skip adding it in the first place:
var s = '';
n.each(function() {
s += (s.length > 0 ? ',' : '') + $(this).val();
});
Using substring
var strNumber = "3623,3635,";
document.write(strNumber.substring(0, strNumber.length - 1));
Using slice
document.write("3623,3635,".slice(0, -1));
Using map
var strNumber = "3623,3635,";
var arrData = strNumber.split(',');
document.write($.map(arrData, function(value, i) {
return value != "" ? value : null;
}).join(','));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Use Array.join
var strNumber = "3623,3635,";
var arrTemp = strNumber.split(',');
var arrData = [];
$.each(arrTemp, function(key, value) {
//document.writeln(value);
if (value != "")
arrData.push(value);
});
document.write(arrData.join(', '));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Using 'normal' javascript:
var truncated = s.substring(0, s.length - 1);
A more primitive way is to change the each loop into a for loop
for(var x = 0; x < n.length; x++ ) {
if(x < n.length - 1)
s += $(n[x]).val() + ",";
else
s += $(n[x]).val();
}
Sam's answer is the best so far, but I think map would be a better choice than each in this case. You're transforming a list of elements into a list of their values, and that's exactly the sort of thing map is designed for.
var list = $("td.title_listing input:checked")
.map(function() { return $(this).val(); })
.get().join(', ');
Edit: Whoops, I missed that CMS beat me to the use of map, he just hid it under a slice suggestion that I skipped over.
you can use below extension method:
String.prototype.trimEnd = function (c) {
c = c ? c : ' ';
var i = this.length - 1;
for (; i >= 0 && this.charAt(i) == c; i--);
return this.substring(0, i + 1);
}
So that you can use it like :
var str="hello,";
str.trimEnd(',');
Output: hello.
for more extension methods, check below link:
Javascript helper methods
Here is a simple method:
var str = '1,2,3,4,5,6,';
strclean = str+'#';
strclean = $.trim(strclean.replace(/,#/g, ''));
strclean = $.trim(str.replace(/#/g, ''));
s = s.TrimEnd(",".ToCharArray());
Write a javascript function :
var removeLastChar = function(value, char){
var lastChar = value.slice(-1);
if(lastChar == char) {
value = value.slice(0, -1);
}
return value;
}
Use it like this:
var nums = '1,2,3,4,5,6,';
var result = removeLastChar(nums, ',');
console.log(result);
jsfiddle demo
Related
I want an eval() function which will calculate brackets as same as normal calculations but here is my code
var str = "2(3)+2(5)+7(2)+2"
var w = 0;
var output = str.split("").map(function(v, i) {
var x = ""
var m = v.indexOf("(")
if (m == 0) {
x += str[i - 1] * str[i + 1]
}
return x;
}).join("")
console.log(eval(output))
Which takes the string str as input but outputs 61014 and whenever I try evaluating the output string, it remains same.
Obligatory "eval() is evil"
In this case, you can probably parse the input. Something like...
var str = "2(3)+2(5)+7(2)+2";
var out = str.replace(/(\d+)\((\d+)\)/g,(_,a,b)=>+a*b);
console.log(out);
while( out.indexOf("+") > -1) {
out = out.replace(/(\d+)\+(\d+)/g,(_,a,b)=>+a+(+b));
}
console.log(out);
You can do it much simplier, just insert '*' in a right positions before brackets
var str = "2(3)+2(5)+7(2)+2"
var output = str.replace(/\d\(/g, v => v[0] + '*' + v[1])
console.log(eval(output))
I am trying to replace all dots for comma and commas for dots and was wondering what is the best practice for doing this. If I do it sequentially, then the steps will overwrite each other.
For example:
1,234.56 (after replacing commas) --> 1.234.56 (after replacing dots) --> 1,234,56
Which is obviously not what I want.
One option I guess is splitting on the characters and joining afterwards using the opposite character. Is there an easier/better way to do this?
You could use a callback
"1,234.56".replace(/[.,]/g, function(x) {
return x == ',' ? '.' : ',';
});
FIDDLE
If you're going to replace more than two characters, you could create a convenience function using a map to do the replacements
function swap(str, swaps) {
var reg = new RegExp('['+Object.keys(swaps).join('')+']','g');
return str.replace(reg, function(x) { return swaps[x] });
}
var map = {
'.':',',
',':'.'
}
var result = swap("1,234.56", map); // 1.234,56
FIDDLE
You could do the following:
var str = '1,234.56';
var map = {',':'.','.':','};
str = str.replace(/[,.]/g, function(k) {
return map[k];
});
Working Demo
Do it in stages using placeholder text:
var foo = '1,234.56';
foo = foo
.replace(',', '~comma~')
.replace('.', '~dot~')
.replace('~comma~', '.')
.replace('~dot~', ',')
You could use a for loop. Something like:
var txt = document.getElementById("txt");
var newStr = "";
for (var i = 0; i < txt.innerHTML.length; i++){
var char = txt.innerHTML.charAt(i);
if (char == "."){
char = ",";
}else if (char == ","){
char = ".";
}
newStr += char;
}
txt.innerHTML = newStr;
Here's a fiddle:
http://jsfiddle.net/AyLQt/1/
Have to say though, #adenoeo's answer is way more slick :D
In javascript you can use
var value = '1.000.000,55';
var splitValue = value.split('.');
for (var i = 0; i < splitValue.length; i++) {
var valPart = splitValue[i];
var newValPart = valPart.replace(',', '.');
splitValue[i] = newValPart;
}
var newValue = splitValue.join(',');
console.log(newValue);
I have a JavaScript string sentrptg2c#appqueue#sentrptg2c#vwemployees#.
I want to get last string vwemployees through RegExp or from any JavaScript function.
Please suggest a way to do this in JavaScript.
You can use the split function:
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
str = str.split("#");
str = str[str.length-2];
alert(str);
// Output: vwemployees
The reason for -2 is because of the trailing #. If there was no trailing #, it would be -1.
Here's a JSFiddle.
var s = "...#value#";
var re = /#([^#]+)#^/;
var answer = re.match(s)[1] || null;
if you're sure the string will be separated by "#" then you can split on # and take the last entry... I'm stripping off the last #, if it's there, before splitting the string.
var initialString = "sentrptg2c#appqueue#sentrptg2c#vwemployees#"
var parts = initialString.replace(/\#$/,"").split("#"); //this produces an array
if(parts.length > 0){
var result = parts[parts.length-1];
}
Try something like this:
String.prototype.between = function(prefix, suffix) {
s = this;
var i = s.indexOf(prefix);
if (i >= 0) {
s = s.substring(i + prefix.length);
}
else {
return '';
}
if (suffix) {
i = s.indexOf(suffix);
if (i >= 0) {
s = s.substring(0, i);
}
else {
return '';
}
}
return s;
}
No magic numbers:
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
var ar = [];
ar = str.split('#');
ar.pop();
var o = ar.pop();
alert(o);
jsfiddle example
I want to remove all empty values from an url:
var s="value1=a&value2=&value3=b&value4=c&value5=";
s = s.replace(...???...);
alert(s);
Expected output:
value1=a&value3=b&value4=c
I only need the query part of the URL to be taken into account.
Something like this:
s = s.replace(/[^=&]+=(&|$)/g,"").replace(/&$/,"");
That is, remove groups of one or more non-equals/non-ampersand characters that are followed by an equals sign and ampersand or end of string. Then remove any leftover trailing ampersand.
Demo: http://jsfiddle.net/pKHzr/
s = s.replace(/[^?=&]+=(&|$)/g,"").replace(/&$/,"");
Added a '?' to nnnnnn's answer to fix the issue where the first parameter is empty in a full URL.
This should do the trick:
var s="value1=a&value2=&value3=b&value4=c&value5=";
var tmp = s.split('&')
var newS = '';
for(var i in a) {
var t = a[i];
if(t[t.length - 1] !== '=') {
newS += t + '&';
}
}
if(newS[newS.length - 1] === '&') {
newS = newS.substr(0, newS.length - 1);
}
console.log(newS);
I don't find any solution to do that with one Regex expression.
But you could loop through your string and construct a new result string : http://jsfiddle.net/UQTY2/3/
var s="value1=a&value2=&value3=b&value4=c&value5=";
var tmpArray = s.split('&');
var final = '';
for(var i=0 ; i<tmpArray.length ; i++)
if(tmpArray[i].split('=')[1] != '')
final += tmpArray[i] + '&';
final = final.substr(0,final.length-1)
alert(final)
Where do you take all the values?
I suggest using an array:
function getValues(str){
var values = [];
var s = str.split('&');
for(var val in s){//source is a
var split = val.split('=');
if(split [1] != '' && split [1] != null){
values.push(val);
}
}
return values.join('&');
}
This is my integer value
12232445
and i need to get like this.
12,232,445
Using prototype how to get this?
var number = 12232445,
value = number.toString(),
parts = new Array;
while (value.length) {
parts.unshift(value.substr(-3));
value = value.substr(0, value.length - 3);
}
number = parts.join(',');
alert(number); // 12,232,445
It might not be the cleanest solution, but it'll do:
function addCommas(n)
{
var str = String(n);
var result = '';
for(var i = 0; i < str.length; i++)
{
if((i - str.length) % 3 == 0)
result += ',';
result += str[i];
}
return result;
}
Here is the function I use, to format thousands separators and takes into account decimals if any:
function thousands(s) {
var rx = /(-?\d+)(\d{3})/,
intDec = (''+s)
.replace(new RegExp('\\' + $b.localisation.thousandSeparator,'g'), '')
.split('\\' + $b.user.localisation.decimalFormat),
intPart = intDec[0],
decPart = intDec[1] || '';
while (rx.test(intPart)) {
intPart = intPart.replace(rx,'$1'+$b.localisation.thousandSeparator+'$2');
}
return intPart + (decPart && $b.localisation.decimalFormat) + decPart;
}
thousands(1234.56) //--> 1,234.56
$b.localisation is a global variable used for the session.
$b.localisation.thousands can have the values , or . or a space.
And $b.localisation.decimalFormat can have the values , or . depending on the locale of the user