Why can I not insert a substring into an array using splice()? - javascript

Excuse the petty question, but this is really nagging me. I'm following the mozilla example: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
Can someone explain why this doesn't work:
<body>
<p id="test">
</p>
</body>
var url = "teststring";
document.getElementById("test").innerHTML = (url.split('').splice(2,0,"teststring").join(''));
jsFiddle: https://jsfiddle.net/uyk2p437/1/

The Array#splice method returns an array containing removed elements, in your case, it would be empty and you are applying Array#join method which generates an empty string.
Use String#slice ( or String#substring) method instead :
url.slice(0, 2) + "teststring" + url.slice(2)
var url = "teststring";
document.getElementById("test").innerHTML = url.slice(0, 2) + "1" + url.slice(2);
<body>
<p id="test">
</p>
</body>

Because the return value from splice is the removed items. Not the modified array. It modifies in place
As per MDN
Return value
An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.
var url = "teststring";
var split = url.split('');
split.splice(2,0,"teststring"); // this returns an empty array because you aren't removing anything
// but the value in split is now:
// ['t','e','t','e','s','t','s','t','r','i','n','g','s','t','s','t','r','i','n','g']
console.log(split.join('')); // gives you the expected result
Or you can use slice as in Pranav's answer, or substr or substring.

Related

Single array[0] item is returning undefined

all devs smarter than me,
So basically I've got a name(first) input field, I want to let the user enter their first name and last name into that input. After that, I want to take the 2nd value(last name) and push the value into another input which is hidden(display:none). So the code below, in theory, should do it
var array = [];
var fullname = $("#firstName").value.split(" ");
array.push(fullname);
$("#lastName").value = array[1];
alert(array[1])
For example iI i put in "First Last" as the name values in the firstName input and split and push to array, if I alert it alert(array) or $("#lastName").value = array, it does push the correct values, however when I try to alert or set only the 2nd part of the array[1] it keeps coming back as undefined!? Please enlighten me my friends.
Firstly, jQuery uses the val() method to retrieve the value of a form element. Attempting to access the value property will return nothing.
That aside, your issue is because you're creating a nested array by pushing the result of split() (ie. an array) in to array:
var fullname = $("#firstName").val().split(" ");
var array = [];
array.push(fullname);
console.log(array)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="firstName" value="Foo Bar" />
Instead, just work with the result of split() directly, without calling push():
var fullname = $("#firstName").val();
var array = fullname.split(' ');
console.log(array[1]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="firstName" value="Foo Bar" />
This is obviously a basic example. You would also need to ensure that the resulting array has at least 2 elements in it.
you have some syntax issues as:
var array = [];
var fullname = $("#firstName").val();
array=fullname.split(" ");
$("#lastName").val(array[1]);
alert(array[1]);
You want to push an array values to an array, instead of array.push(fullname);, use
array.push.apply( array , fullname);
or
array = array.concat(fullName);
In your code, use $("#lastName").val() instead of $("#lastName").value. You are using array[] instead of array constructor(). E.g: var a = array[1] returns 1 which means value of a
= 1.
Kindly check the link: Difference between new Array() and [ ]

Remove selector criteria in variable value

I'm creating an online shop, with specific links to products e.g. (http://example.com/products/phones/nexus-5).
I'm using the following code,
var get_product_availability_classname = $("[class$='_availability']").attr('class');
which selects (creates a variable with the value of) the element that has a class ending in "_availability".
Every product page has a different piece of text just before the _availability, like GOOGLENEXUS5_availability, SAMSUNG4KTV_availability, whatever_availability...
What I have to do now is to essentially remove the criteria I used to get that whole class name (i.e. class$='_availability'); using the example above it'd be trimmed from SAMSUNG4KTV_availability to SAMSUNG4KTV.
Possible solutions
I haven't figured how to, but we could use JavaScript's substring() or substr().
You will be best off using Regex in this situation. The following will look for the _availability in the classes string and if it finds it it will capture what came before.
var get_product_availability_classname = $("[class$='_availability']").attr('class');
var matches = /([^\s]*)_availability\b/g.exec(get_product_availability_classname)
if(matches.length > 1){
var your_id = matches[1];
}
Use attr() method with a callback and update the class name using String#replace method with word boundary regex.
Although use attribute contains selector since there is a chance to have multiple classes, in that case, the class can be at the start or between two classes.
var get_product_availability_classname = $("[class*='_availability '],[class$='_availability']");
get_product_availability_classname.attr('class',function(i,v){
return v.replace(/_availability\b/g,'');
});
var get_product_availability_classname = $("[class*='_availability '],[class$='_availability']");
get_product_availability_classname.attr('class', function(i, v) {
return v.replace(/_availability\b/, '');
});
console.log(document.body.innerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="abc_availability"></div>
<div class="abc_availability class"></div>
<div class="class abc_availability"></div>
<div class="class abc_availability class1"></div>
If there will only ever be a single _ in the class name
var get_product_availability_classname = $("[class$='_availability']").attr('class')
.split(' ') // split the class to individual classes
.filter(function(cls) { // filter ones with _availability
return cls.split('_').pop() == 'availability');
})[0]; // use first match
var product = get_product_availability_classname.split('_')[0]
.split('_') creates an array ["PRODUCT", "availability"] and the [0] selects the first item of this array
alternatively you could also
var product = get_product_availability_classname.split('_availability')[0]
this does the same thing, except it splits on the string _availability, and it doesn't matter how many _ in the prefix
If your string is always in the form x_y, where x and y don't contain an underscore, then you can use the split function to split on the underscore.
var str = "SAMSUNG4KTV_availability";
var result = str.split("_")[0];
console.log(result);
The split function returns an array of strings containing the substring in between each underscore, you use [0] to select the first element in the array.

Object doesn't support property or method 'slice'

I'm newbie to the Javascript/Jquery world.
I have a div with several links and i want to collect the url's .
Then i want to extract from those href's the last 9 characters (actually i wish to optimize it and collect the digits independently the length at the end of each string).I tried to extract them with the slice() method but it does not work.
In console the error is
Object doesn't support property or method 'slice'
Can i convert the object to a string ? Your help is appreciated !
The code is the following
$(document).ready(function(){
var $posts= $('a.entry_title').each(function(){
$(this).attr('href');
});
var posts1 = $posts[0].slice(-9);
var posts2 = $posts[1].slice(-9);
var posts = ["MyURL"+ posts1,"MyURL"+posts2]
$('#div1').load(posts[0] + " .shadow3");
$('#div2').load(posts[1] + " .shadow3");
});
</script>
You see Object doesn't support because $.each returns a jQuery object.
Use .map() instead because it returns an array on which slice would work
var $posts= $('a.entry_title').map(function(){
return $(this).attr('href');
});
Result would be
["link1", "link2", "link3"....] // just a sample
If you wish to get an array of hrefs with last nine characters of each link you can use map this way
var $posts= $('a.entry_title').map(function(){
return $(this).attr('href').slice(-9); // or you can do your own magic
});
Result would look like this
["k1", "k2", "k3"....] // after slicing the words
Try next one:
var hrefs = []; // list of collected and sliced hrefs.
var $posts= $('a.entry_title').each(function() {
// slice & push each href into list.
hrefs.push($(this).attr('href').slice(-9));
});
console.log('href list:', hrefs); // control result.
var posts = ["MyURL"+ hrefs[0],"MyURL"+hrefs[1]]

How to deep copy string in javascript?

I'm new to JavaScript and have a basic question. I have 2 text fields on a server-generated page, and I want to copy the text value of field 1 to field 2, and then set field 1's value to an empty string. The problem is since JavaScript is doing a shallow copy, field 2's value is set to an empty string as well.
Here is the code:
var eleTxtInit = document.getElementById("InputText0");
if (eleTxtInit == null) {
eleTxtInit = document.getElementsByName("InputText0");
}
var eleTxtControl = document.getElementById("InputText1");
if (eleTxtControl == null) {
eleTxtControl = document.getElementsByName("InputText1");
}
eleTxtControl.value = eleTxtInit.value;
eleTxtInit.value = "";
The result of the above code is that InputText1 value becomes "" as well :( ..
What's the solution here ?
I think your problem is: eleTxtControl = document.getElementsByName("InputText1");. getElementsByName returns a Nodelist, so you should use
eleTxtInit = document.getElementsByName("InputText0")[0];
//and ofcourse
eleTxtControl = document.getElementsByName("InputText1")[0];
See jsfiddle
eleTxtInit = document.getElementsByName("InputText0");
triggering will result in the subsequent code failure, since document.getElementsByName returns an HTMLCollection, not an Element. Ditto for eleTxtControl.

Splice method does not remove array

I have a javascript that has custom indexes, I created them like so:
var rand = event.timeStamp; //jquery on click event object
freeze_array[rand] = month + ',' + model_name + ',' + activity;
To remove the above element I have this:
freeze_array.splice(rand, 1);
But this does not remove the element as I can see it in my firebug dom object viewer. Here is an example of the array:
My indexes are in the form: 1283519490632 - too long to be an integer that is required by the splice method?
Thanks all for any help
As you mentioned, the index argument must be an integer. Maybe you can use an object that holds indices as follows:
var lastIndex=0; // that shall be global...
var pointer = {};
....
pointer[rand] = lastIndex;
++lastIndex;
Then use it as follows:
freeze_array = freeze_array.splice(pointer[rand], 1);
Yes the index must be an integer. Your value is too large for a integer.
See at w3schools
index: Required. An integer that
specifies at what position to
add/remove elements
Try this:
delete freeze_array[ rand ];

Categories