This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 27 days ago.
Hi i am working in java script i have a string
var data = 'http://baab.bh/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/t/e/test.jpg';
i want to replace /image/ into 'image/440x600' i am using this function
.replace()
but its not working here is my code
var data ='http://baab.bh/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/t/e/test.jpg';
data.replace('/image/', '/image/440x600/');
console.log(data);
its showing same not replacing /image/ into 'image/440x600'.
Strings in JavaScript are immutable. They cannot be modified.
The replace method returns the modified string, it doesn't modify the original in place.
You need to capture its return value.
var data = 'http://baab.bh/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/t/e/test.jpg';
data = data.replace('/image/', '/image/440x600/');
console.log(data);
Strings in JavaScript are immutable. Thus the replace function doesn't change the string but returns a new one, you have to use the returned value:
var data = data.replace('/image/', '/image/440x600/');
//Your Actual Data
var data ='http://baab.bh/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/t/e/test.jpg';
// Changing the reference of the Actual Data and gets a new String
var ChangedData =data.replace('/image/', '/image/440x600/');
// To Verify the Output
console.log(data);
console.log(ChangedData);
Please check this
var str = "http://baab.bh/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/t/e/test.jpg";
var res = str.replace("image", "image/440x600");
console.log(res);
Using global regular expression
var data = data.replace(/image/g, '/image/440x600/');
Related
This question already has answers here:
How do I split a string, breaking at a particular character?
(17 answers)
Closed 2 years ago.
I get one string by query like '5e6,5e4,123'.
And I want to make an array containing this query as below in JS.
['5e6', '5e4', '123']
How can I make this? Thank you so much for reading it.
You can use .split(',')
var str = "5e6,5e4,123";
var array = str.split(',');
console.log(array);
You can read more on this here
Use String.split:
console.log('5e6,5e4,123'.split(","))
var query = '5e6,5e4,123';
var queries = query.split(‘,’);
You can make use of split method of string like below:
var res = str.split(',');
const output = input.split(',');
I have this code:
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
localStorage.setItem('added-items', JSON.stringify(string));
This code will use localStorage.
Here is now the code to get the stored data:
var retrievedObject = localStorage.getItem('added-items');
My problem now is, how can i get the size of the data items? answer must be 2.
How can i get the "Item1" and "Item2"?
I tried retrievedObject[0][0] but it is not working.
And how to add data on it?
so it will be
{"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]}
Can I use JSON.stringify?
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
localStorage.setItem('added-items', JSON.stringify(string));
stringify means, take an object and return its presentation as a string.
What you have, is already a string and not a JSON object.
The opposite is JSON.parse which takes a string and turns it into an object.
Neither of them have anything to do with getting the size of an array. When properly coding JavaScript you almost never use JSON.parse or JSON.stringify. Only if serialization is explicitly wanted.
Use length for the size of the array:
var obj = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]}
console.debug(obj.items.length);
// THIS IS ALREADY STRINGIFIED
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
// DO NOT STRINGIFY AGAIN WHEN WRITING TO LOCAL STORAGE
localStorage.setItem('added-items', string);
// READ STRING FROM LOCAL STORAGE
var retrievedObject = localStorage.getItem('added-items');
// CONVERT STRING TO REGULAR JS OBJECT
var parsedObject = JSON.parse(retrievedObject);
// ACCESS DATA
console.log(parsedObject.items[0].Desc);
To bring clarity to future people that may stumble across this question and found the accepted answer to not be everything you hoped and dreamed for:
I've extended the question so that the user may either want to input a string or JSON into localStorage.
Included are two functions, AddToLocalStorage(data) and GetFromLocalStorage(key).
With AddToLocalStorage(data), if your input is not a string (such as JSON), then it will be converted into one.
GetFromLocalStorage(key) retrieves the data from localStorage of said key
The end of the script shows an example of how to examine and alter the data within JSON. Because it is a combination of objects and array, one must use a combination of . and [] where they are applicable.
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
var json = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"firstName":"John"},{"lastName":"Smith"}]};
localStorage.setItem('added-items', AddToLocalStorage(string));
localStorage.setItem('added-items', AddToLocalStorage(json));
// this function converts JSON into string to be entered into localStorage
function AddToLocalStorage(data) {
if (typeof data != "string") {data = JSON.stringify(data);}
return data;
}
// this function gets string from localStorage and converts it into JSON
function GetFromLocalStorage(key) {
return JSON.parse(localStorage.getItem(key));
}
var myData = GetFromLocalStorage("added-items");
console.log(myData.items[2].firstName) // "John"
myData.items[2].firstName = ["John","Elizabeth"];
myData.items[2].lastName = ["Smith","Howard"];
console.log(myData.items[2]) // {"firstName":["John","Elizabeth"],"lastName":["Smith","Howard"]}
console.log(myData.items.length) // 4
JSON.parse is definitely the best way to create an object but I just want to add if that doesn't work (because of lack of support), obj = eval('(' + str + ')'); should work. I've had a problem with a HTML to PDF converter in the past that didn't include JSON.parse and eval did the trick. Try JSON.parse first.
Access your object: obj.items[0].Desc;
var object = Json.parse(retrievedObject);
Now you can access it just like an array
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
If you need more help i have some previous code where i am reading Json from local storage and making a form from that json. This code will help in understanding how to traverse that array
Json stored in localstorage
{"form":[{"element":"input", "type":"text","name":"name","value":"value","min":"2","max":"10"}]}
JavaScript to read that json
function readJson(){
if(!form_created){
add_form();
}
var fetched_json = localStorage.getItem("json");
var obj=JSON.parse(fetched_json);
for(var i=0; i<obj.form.length;i++){
var input = document.createElement(obj.form[i].element);
input.name = obj.form[i].name;
input.value = obj.form[i].value;
input.type = obj.form[i].type;
input.dataset.min = obj.form[i].min;
input.dataset.max = obj.form[i].max;
input.dataset.optional = obj.form[i].optional;
form.insertBefore (input,form.lastChild);
}
alert(obj.form[0].name);
}
This question already has answers here:
How to get the first element of an array?
(35 answers)
Closed 8 years ago.
I am trying to get the first word out of the variable var solution = [cow, pig]
I have tried everything from strings to arrays and I can't get it. Please help.
As per the comments
solution[0]
Will return the first item in the array.
solution[1]
would be the second, or undefined if the array was:
var solution = [cow]
Is solution an array, or is it in that form? (var solution = [cow, pig]) You also need to add quotes around those values, unless those values are defined variables.
You need to change the variable to look like this:
var solution = ['cow', 'pig']
If so, just get the value at subscript 0.
var result = solution[0];
console.log(result);
If you mean an string like
solution = "cow pig".
Do
solution = solution.split(' ')[0];
console.log(solution); //Will return cow
i have a json string returned to a hidden value and i want to assign it to a javascript array and print each element of the array.
Json string returned by hdn_client_windows - ["5703","5704"]
Javascript array assignment is as below.
var times = $('#hdn_client_windows').val();
alert(times[0]); // this printed only--> [
alert(times[1]); // this printed only--> "
what am i doing wrong ?
You need to parse the JSON into an array with JSON.parse first:
var times = JSON.parse($('#hdn_client_windows').val());
Since you are already using jQuery, it might be a good idea to defer to $.parseJSON instead just to be on the safe side (full compatibility with old browsers):
var times = $.parseJSON($('#hdn_client_windows').val());
Use $.parseJSON().
var str = '["5703","5704"]';
var times = $.parseJSON( str );
You have to parse the string first using JSON.parse (older browsers might require you to load this in):
var times = JSON.parse($('#hdn_client_windows').val());
alert(times[0]); // Will display first item
alert(times[1]); // Will display second item
You could use jquery's parseJSON() function.
var str = '["5703","5704"]';
var parsed = $.parseJSON( str );
The parsed object now contains the array: ["5703","5704"]
Reference - jQuery.parseJSON( json )
"Takes a well-formed JSON string and returns the resulting JavaScript object."
i have this static code that will hide/show some combo box but what if i add more category´s ?well if do add more category´s i have to change the code every time
so what i want to do is have a var that will receive several values separated by comma
and them some how it will separate the values and them it will store the values in a array. and now when the user needs to add more category´s i don't have to edit the code.
but how can i separate the values divided by a comma and then add them to a array?
If I understand your question correctly you'll want to have a look at http://www.w3schools.com/jsref/jsref_split.asp
And use var arr = YOURVARIABLE.split(',');
You can use the String.split() function, e.g:
var s = '1,2,3,4,5,6';
var values = s.split(',');
console.log(values);
For more information see here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split
You would use the split() method. http://www.w3schools.com/jsref/jsref_split.asp
var string = '1,2,3,text,123';
var array = string.split(',');
//array = [1, 2, 3, 'text', 123];
Try the following code
var testString = "comma,seperated,list";
var stringArr = testString.split(",");
the split() method will literally split the string by the delimeter passed to it and return an array of values. in this case our array will be
// stringArr = ["comma", "seperated", "list"];