I have a url like "http://localhost:8080/myapp?age=12&add=mumbai&name=myname"
Now I want to add one parameter(tel=12345) as the first parameter in the query string like
"http://localhost:8080/myapp?tel=12345&age=12&add=mumbai&name=myname"
I have tried below snippet
var str = "http://localhost:8080/myapp?age=12&add=mumbai&name=myname";
var txt2 = str.slice(0, str.indexOf("?")) + "tel=12345&" + str.slice(str.indexOf("?"));
alert(txt2);
But the result is incorrect
http://localhost:8080/myapptel=12345&?age=12&add=mumbai&name=myname
Is there a better way???
Try this:
var str = "http://localhost:8080/myapp?age=12&add=mumbai&name=myname";
var txt2 = str.slice(0, str.indexOf("?")) + "?" + "tel=12345&"
// ^^^^^
+ str.slice(str.indexOf("?") + 1);
// ^^^
alert(txt2);
You need to just increment index by 1 and this will work.
E.g.:
var txt2 = str.slice(0, str.indexOf("?") + 1 ) + "tel=12345&" + str.slice(str.indexOf("?") + 1);
var txt2=str.split('?')[0]+'?tel=12345&'+str.split('?')[1];
Just a variation.
function generateBC(url, separator) {
var splitthis = url.split("/");
var MiddleBit = [];
var RemoveFirstElement = splitthis.shift();
var RemoveLastElement = splitthis.pop();
var RemoveLastElementDot = RemoveLastElement.substring(0, RemoveLastElement.indexOf('.')).toUpperCase();
var arrayLength = splitthis.length;
for (var i = 0; i < arrayLength; i++) {
var elementOk = splitthis[i].toUpperCase();
var urlOk = "<a href='/pictures/'>" + elementOk + "</a>";
MiddleBit.push(urlOk);
}
var ConMiddleBitS = String(MiddleBit).replace(/,/g , separator);
var completed = 'HOME ' + separator + ConMiddleBitS + separator + "<span class='active'>" + RemoveLastElementDot + "</span>" ;
document.write(completed);
}
generateBC("mysite.com/pictures/hotels/tens/holidays.html", " : ");
I don't know why I get
TypeError: Cannot call method 'replace' of undefined
at compareResults` on .replace() ?
Can someone please explain why, as I see nothing wrong with the above.
Thank-you!
It seems that you're trying to use a String method on an array. Have you tried joining the array and the using the replace() method?
var ConMiddleBitS = MiddleBit.join('').replace(/,/g , separator);
EDIT:
If you're trying to remove the , from the array you don't have to use replace, you can just do MiddleBit = MiddleBit.join(separator).
I have the following code segment:
function test(){
try {
---------------some contents-------
}
catch(e){
}
}
Now, I want the codes between the 1st pair of curly braces. The output should be like:
try {
---------------some contents-------
}
catch(e){
}
How can I do that with or without using Regex? I tried using the following regex:
Pattern p = Pattern.compile("\\{([^}]*)\\}");
Matcher m = p.matcher(s); // s contains each line of the above text
while (m.find()) {
System.out.println(m.group(1));
}
But, It only fetches contents if its there in a single line or no multiple lines of braces exist.
You could've searched better
Use substr and indexOf / lastIndexOf:
function test(){
try { /*---------------some contents-------*/ }
catch(e) {}
}
var testStr = String(test);
testStr = testStr.substr(testStr.indexOf('{') + 1);
document.querySelector('#result').textContent =
testStr.substr(0, testStr.lastIndexOf('}'));
<pre id="result"></pre>
Just Try It:
String s = "function test(){"
+ "try {"
+ "---------------some contents-------"
+ "}"
+ "catch(e){"
+ "}"
+ "}";
int bracketStartIndex = s.indexOf("{");
System.out.println("START INDEX = " + bracketStartIndex);
int bracketEndIndex = s.lastIndexOf("}");
System.out.println("END INDEX = " + bracketEndIndex);
System.out.println("OUTPUT STRING : " + s.substring(bracketStartIndex, bracketEndIndex));
I want to loop through my json response. My json response looks like this
{"line":[{"type":"bank","name":"ABN","account":"NL47ABNA0442660960","description":"Bijgewerkt t\/m 30-10-2014","balance":"6.266,55","image":""},{"type":"bank","name":"Rabo","account":"NL89RABO0177896647","description":"","balance":"0,00","image":""}],"total":"6.266,55"}
What I want is a foreach loop through all lines so i get the keys and the values for every line.
You could iterate like this: (added code-comments for explanation)
var result = document.getElementById("result");
var json = '{"line":[{"type":"bank","name":"ABN","account":"NL47ABNA0442660960","description":"Bijgewerkt t\/m 30-10-2014","balance":"6.266,55","image":""},{"type":"bank","name":"Rabo","account":"NL89RABO0177896647","description":"","balance":"0,00","image":""}],"total":"6.266,55"}';
var obj = JSON.parse(json);
// json object contains two properties: "line" and "total".
// iterate "line" property (which is an array but that can be iterated)
for (var key in obj.line) {
// key here is the index of line array
result.innerHTML += "<br/>" + key + ": ";
// each element of line array is an object
// so we can iterate over its properties
for (var prop in obj.line[key]) {
// prop here is the property
// obj.line[key][prop] is the value at this index and for this prop
result.innerHTML += "<br/>" + prop + " = " + obj.line[key][prop];
}
}
// "total" is a property on the root object
result.innerHTML += "<br/><br/>Total = " + obj.total;
<p id="result"> </p>
Demo Fiddle: http://jsfiddle.net/abhitalks/ajgrLj0h/2/
.
var json = {"line":[{"type":"bank","name":"ABN","account":"NL47ABNA0442660960","description":"Bijgewerkt t\/m 30-10-2014","balance":"6.266,55","image":""},{"type":"bank","name":"Rabo","account":"NL89RABO0177896647","description":"","balance":"0,00","image":""}],"total":"6.266,55"};
for(var i = 0; i < json.line.length; i++)
{
console.log("Type: " + json.line[i].type + " Name: " + json.line[i].name + " Account: " + json.line[i].account + " Description: " + json.line[i].description + " Balance: " + json.line[i].balance + " Image: " + json.line[i].image);
}
You can do something like that...
var json = {"line":[{"type":"bank","name":"ABN","account":"NL47ABNA0442660960","description":"Bijgewerkt t\/m 30-10-2014","balance":"6.266,55","image":""},{"type":"bank","name":"Rabo","account":"NL89RABO0177896647","description":"","balance":"0,00","image":""}],"total":"6.266,55"};
if(json.line !== undefined && json.line.length > 0){
var key,value;
json.line.map(function(lineObject){
for (key in lineObject) {
value = (lineObject[key] == '')?'unknown': lineObject[key];
console.log(key+":"+ value);
}
console.log("---------------------");
});
}
http://jsfiddle.net/ddw7nx91/
var obj = {"line":[]} //your json here
for(var i=0; i<obj.line.length; i++) {
console.log(obj.line[i].type)
}
obj.line is an array, so you can get his length an cycle it.
This would create an array of lines each with a keys object and a values object.
var response = JSON.parse( {'your':'JSON'} );
var lines = [];
$.each( response, function( line ) {//loop through lines in response
var keys = [];
var values = [];
$.each( line, function( obj ) {
keys.push( Object.keys(obj) );//get keys
for( var key in obj ) {
values.push(obj[key]);//get values
}
});
lines.push({ {'keys':keys},{'values':values} });
});
I have a symbol (#) seperated variable as shown below
var inputStr = "IceCreams#Cone";
How can i split this and form a string in java script variable .
With the above input String how can form a string as
Are You Sure to add a Category Under IceCreams => Cone
I have tried as shown below ,but couldn't achive that dynamically
Thanks in advance .
function myFunction(inputStr)
{
var res = inputStr.split('#');
var r = confirm("Are You Sure to add a Category Under" +res[0]+" "+res[1]+" );
if (r == true) {
} else {
}
}
http://jsfiddle.net/4km0k9nv/1/
You code works if you fix your typo.
window.onload = function() {
function myFunction(inputStr) {
var res = inputStr.split('#');
alert("Are You Sure to add a Category Under " + res[0] + " " + res[1] + " ?" );
}
myFunction("Ice#cream");
}
If you just want to replace the "#" symbol, you can use the string replace function.
var str = "part1#part2";
var str2 = str.replace('#', " => ");
Your example should work fine, but it seems to be a typo.
Good Luck
I was messing around with it and I came up with this. Is this what you want? It runs the function on the input element blur.
function myFunction(inputStr)
{
var res = inputStr.split('#');
confirm("Are You Sure to add a Category Under " + res[0] + " => " + res[1] + " ?");
}
<input type="text" onblur="myFunction(this.value)">
Hope this helps!
function myFunction(inputStr)
{
var res = inputStr.split('#');
var r = confirm("Are You Sure to add a Category Under " + res[0] + " => "+ res[1] + "?");
if (r == true) {
addNewCategory(res[0], res[1]); // rename/rewrite this call as needed
} else {
cancelAdd(); // replace this line with whatever you need.
}
}
Alternatively you can say:
var res = inputStr.replace("#", " => ");
var r = confirm("Are You Sure to add a Category Under " + res + "?");
The second bit of code would make res a string instead of an array of strings. Depending on your needs, that may suffice. If you'd like to or need to use res as an array of strings, then the first chunk of code should be all your need.