Hi all I am framing a url with Query string in javascript as follows every thing works fine but a comm is coming in between the query string so can some one help me
<script type="text/javascript">
function RedirectLocation() {
var cntrl = "Q1;Q2";
var str_array = cntrl.split(';');
var cnt = str_array.length;
if (cnt == 0) {
location.href = '/callBack.aspx';
}
else {
var arr = [];
for (var i = 0; i < str_array.length; i++) {
str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
arr.push(str_array[i] + '=1');
if (i != str_array.length - 1) {
arr.push('&');
}
}
location.href = '/Sample.aspx?' + arr;
}
}
</script>
This is giving me the query string as follows Sample.aspx?Q1=1,&,Q2=1 I need this to be like `Sample.aspx?Q1=1&Q2=1
To remove the commas from a string you could simply do
s = s.replace(/,/g,'');
But in your specific case, what you want is not to add the commas. Change
location.href = '/Sample.aspx?' + arr;
to
location.href = '/Sample.aspx?' + arr.join('');
What happens is that adding an array to a string calls toString on that array and that function adds the commas :
""+["a","b"] gives "a,b"
Don't rely on the implicit string conversion (which concatenates the array elements with a comma as separator), explicitly .join the array elements with &:
var arr = [];
for (var i = 0; i < str_array.length; i++) {
str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
arr.push(str_array[i] + '=1');
}
location.href = '/Sample.aspx?' + arr.join('&');
Think about it like this: You have a set of name=value entries which you want to have separated by &.
You can use arr.join(glue) to concatenate Array elements with something inbetween. In your case glue would be an empty string arr.join("").
Related
I have a string csv containing PORTCODE and latitude longitude of location. I use these values to plot the marker on google map.
Eg csv string:
ANC|61.2181:149.9003,
ANC|61.2181:149.9003,
TLK|62.3209:150.1066,
DNL|63.1148:151.1926,
DNL|63.1148:151.1926,
DNL|63.1148:151.1926,
TLK|62.3209:150.1066,
TLK|62.3209:150.1066,
ALE|60.9543:149.1599
i want to autonumber SIMILAR PORTCODE sequence separated with pipe symbol '|' for the PORTCODE which are EXACT Consecutive next element.
Required out put:
ANC|61.2181:149.9003:1|2,
TLK|62.3209:150.1066:3,
DNL|63.1148:151.1926:4|5|6,
TLK|62.3209:150.1066:7|8,
ALE|60.9543:149.1599:9
Any solution using jquery/javascript/c# ?
There's probably a neater/shorter way to do this, but here's the first second way that came to mind using JavaScript:
var input = "ANC|61.2181:149.9003,\nANC|61.2181:149.9003,\nTLK|62.3209:150.1066,\nDNL|63.1148:151.1926,\nDNL|63.1148:151.1926,\nDNL|63.1148:151.1926,\nTLK|62.3209:150.1066,\nTLK|62.3209:150.1066,\nALE|60.9543:149.1599";
var output = input.split(",\n").reduce(function(p,c,i,a) {
if (i === 1) p += ":1";
return p + (c === a[i-1] ? "|" : ",\n" + c + ":") + (i+1);
});
console.log(output);
I've assumed each line ends with a single \n character, but obviously you can adjust for \r or whatever.
Further reading:
the string .split() method
the array .reduce() method
You can make something like that.
var csv = 'ANC|61.2181:149.9003,\nANC|61.2181:149.9003,\nTLK|62.3209:150.1066,\nDNL|63.1148:151.1926,\nDNL|63.1148:151.1926,\nDNL|63.1148:151.1926,\nTLK|62.3209:150.1066,\nTLK|62.3209:150.1066,\nALE|60.9543:149.1599'.split(',\n');
//count entry :
var results = [];
var j = -1;
var previous = "";
for (i = 0; i < csv.length; i++) {
if (previous === csv[i]) {
results [j] += '|' + (i+1);
} else {
j += 1;
previous = csv[i];
results [j] = csv[i] + ':' + (i+1);
}
}
//And reforme your csv
console.log(results.join(',\n'));
Further reading:
the string .split() method
the array .join() method
here is C# way to do,
public string[] data = { "ANC|61.2181:149.9003", "ANC|61.2181:149.9003", "TLK|62.3209:150.1066", "DNL|63.1148:151.1926", "DNL|63.1148:151.1926", "TLK|62.3209:150.1066", "TLK|62.3209:150.1066", "ALE|60.9543:149.1599", "DNL|63.1148:151.1926" };
int counter = 0;
var output = data.Select(x => new Tuple<string, int>(x, counter++))
.GroupBy(x => x.Item1)
.Select(h => h.Key + ":"+ string.Join("|", h.Select(x => x.Item2)));
output would be ANC|61.2181:149.9003:0|1,TLK|62.3209:150.1066:2|5|6,DNL|63.1148:151.1926:3|4|8,ALE|60.9543:149.1599:7
I have string
var string = .row-4 .col-2.grid-unit+.grid-unit+.grid-unit,.row-4 .col-3 .grid-unit .row-4 .grid-unit:nth-of-type(2n+3) .show-grid+.show-grid-reportdiv
and i need to remove all plus sign leaving the plus sign inside the brackets from the string using javascript
I'd go with something along those lines:
var i, splits, string = ".row-4 .col-2.grid-unit+.grid-unit+.grid-unit,.row-4 .col-3 .grid-unit .row-4 .grid-unit:nth-of-type(2n+3) .show-grid+.show-grid-reportdiv";
splits = string.split(/(\([^)]+\))/);
for (i = 0; i< splits.length; i++) {
if (splits[i].charAt(0) !== "(") {
splits[i] = splits[i].replace("+"," ");
}
}
string = splits.join();
Another way around (dunno if it's better performance wise) would be to use the following:
var string = ".row-4 .col-2.grid-unit+.grid-unit+.grid-unit,.row-4 .col-3 .grid-unit .row-4 .grid-unit:nth-of-type(2n+3) .show-grid+.show-grid-reportdiv";
function replacer (match, offset, string) {
var posOpen = string.indexOf("(",offset);
var posClose = string.indexOf(")",offset);
// we replace it if there are no more closing parenthesis or if there is one that is located after an opening one.
if (posClose === -1 || (posClose > posOpen && posOpen !== -1)) {
return " ";
} else {
return "+";
}
};
string.replace(/\+/g, replacer);
EDIT: added bergi suggestion for a quicker check inside the loop.
EDIT2: Second solution
Use the following code, and let me know if it works :)
var myString = ".row-4 .col-2.grid-unit+.grid-unit+.grid-unit,.row-4:nth-of-type(2n+3) .col-3 .grid-unit .row-4 .grid-unit:nth-of-type(2n+3) .show-grid+.show-grid-reportdiv";
var myArray = myString.split(/\(.[\(\)A-Za-z0-9-.+]*\)/);
for(var i = 0; i < myArray.length; i++) {
myString = myString.replace(myArray[i], myArray[i].replace(/[+]/g,' '));
}
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('&');
}
Hoping you guys can help me out.
I have a dynamic url and I need some javascript to basically trim the string after the specific occurrence of a character.
EXAMPLE:
I have this url
Assessment/testdir2/TestDIR3/lecture slides 1as.pdf
and I need to remove everything after the 2nd slash and including the 2nd slash.
How would I do this?
A very basic JS solution:
function removeAfterSlash(word, numberOfElements) {
var splitWord = word.split('/');
var newWord = '';
for(var i = 0; i < numberOfElements; i++) {
if(i != (numberOfElements - 1)) {
newWord += splitWord[i] + '/';
} else {
newWord += splitWord[i];
}
}
document.write(newWord);
}
removeAfterSlash('Assessment/testdir2/TestDIR3/lecture slides 1as.pdf', 1);
Simply split's the word into an array by looking for a / and then you can join the elements you need back together. The function takes the word and how many 'segments' you want to join back together.
See it on jsfiddle.
Try this:
var url= "Assessment/testdir2/TestDIR3/lecture slides 1as.pdf"
var locs = myString.split('/');
var newUrl = "";
for (var i = 2; i < locs.length; i ++) {
newUrl += "/" + locs[i];
}
This method will then ignore the first two folders and will work regardless of how many other folders you have in the url.
friends.
I have an array and it contains some string values.
ex: array name="All_array"
Now i want to check all values in that array for first character of a string.
if a String starts with character 'a' then move that string to array called "A_array".
if a String starts with character 'b' then move that string to array called "B_array".
How to achieve this task.
var splitArrays = {};
for(var i = 0; i < All_array.length; ++i){
var firstChar = All_array[i].substr(0,1).toUpperCase();
if(!splitArrays[firstChar + '_array'])
splitArrays[firstChar + '_array'] = [];
splitArrays[firstChar + '_array'].push(All_array[i]);
}
This will take every element in All_array and put them into an object containing the arrays indexed by the first letter of the elements in All_array, like this:
splitArrays.A_array = ['Abcd','Anej','Aali']
etc...
Here's a fiddle: http://jsfiddle.net/svjJ9/
The code would be this:
for(var i=0; i<All_array.length; i++){
var firstChar = All_array[i].substr(0, 1).toUpperCase();
var arrayName = firstChar + "_array";
if(typeof(window[arrayName]) == 'undefined') window[arrayName] = []; //Create the var if it doesn't exist
window[arrayName].push(All_array[i]);
}
A_array = []; //empty the array (cause you wanted to 'move')
Hope this helps. Cheers
You could do it using each() and charAt:
$.each(All_array,function(i,s){
var c = s.charAt(0).toUpperCase();
if(!window[c + '_array']) window[c + '_array'] = [];
window[c + '_array'].push(s);
});