jquery or javascript array appending to div as a text - javascript

my problem is with appending a array into existing div as a text. I cant figure it out why its not working, so i have this code:
var raya = ui.item.value + ' ';
$('#result').append(raya);
var tor = $("#result").text();
Above code is working, the value of raya (which is string) is appended correctly into #result
Problem comes here, the value of array1 is not appended to #result2 and ideas why its not working?
var array1 = new Array();
array1 = tor.split( " " );
array1 = $.unique(array1);
$('#result2').append(array1);
return false;
(just to mention that everything is holded in 1 function, this cant be the reason, but just to know)

That's because append expects a string and you're sending it an array.
Two ways to solve it. Use either .toString() or .join()
$('#result2').append(array1.toString()); //inserts a comma separated list
$('#result2').append(array1.join(' ')); //inserts a string separated by what you pass as param

you can do something like this to explicitly convert array to string.
$('#result2').append(array1+'');
Here's a working example
http://jsfiddle.net/EsnLs/2/

Related

Array to Newline String to Array again through HTML

I have an array that comes in from from my API that I would like to arrange in a way that is better for the user (namely, in a column as opposed to the typical comma separated printed array).
This is my JS Fiddle to give a clearer picture: https://jsfiddle.net/2z89owas/
My question is, how can I get output3 to display just like output (and maintain its status as an iterable array like it was as dates)?
First you should not be using value for an html element. You can use .value for extracting value from inputs. Change your line to:
var val = document.getElementById('output2').innerHTML;
Afterwards, you have to split the same way you did join.
var dates3 = val.split('<br>');
document.getElementById('output3').innerHTML = dates3;
You can directly use join, something like:
document.getElementById('output3').innerHTML = dates.join(',');
You can try mapping over the contents of dates instead, as so:
let datesElem = dates.map(date =>`<p>${date}</p>`);
// test: console.log(datesElem)
document.getElementById('output3').innerHTML = datesElem

Dynamic string cutting

Okay, so I have a filepath with a variable prefix...
C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade
... now this path will be different for whatever computer I'm working on...
is there a way to traverse the string up to say 'secc-electron\', and drop it and everything before it while preserving the rest of it? I'm familiar with converting strings to arrays to manipulate elements contained within delimiters, but this is a problem that I have yet to come up with an answer to... would there be some sort of regex solution instead? I'm not that great with regex so I wouldn't know where to begin...
What you probably want is to do a split (with regex or not):
Here's an example:
var paragraph = 'C:\\Users\\susan ivey\\Documents\\VKS Projects\\secc-electron\\src\\views\\main.jade';
var splittedString = paragraph.split("secc-electron"); // returns an array of 2 element containing "C:\\Users\\susan ivey\\Documents\\VKS Projects\\" as the first element and "\\src\\views\\main.jade" as the 2nd element
console.log(splittedString[1]);
You can have a look at this https://www.w3schools.com/jsref/jsref_split.asp to learn more about this function.
With Regex you can do:
var myPath = 'C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade'
var relativePath = myPath.replace(/.*(?=secc-electron)/, '');
The Regex is:
.*(?=secc-electron)
It matches any characters up to 'secc-electron'. When calling replace it will return the last part of the path.
You can split the string at a certain point, then return the second part of the resulting array:
var string = "C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade"
console.log('string is: ', string)
var newArray = string.split("secc-electron")
console.log('newArray is: ', newArray)
console.log('newArray[1] is: ', newArray[1])
Alternatively you could use path.parse(path); https://nodejs.org/api/path.html#path_path_parse_path and retrieve the parts that you are interested in from the object that gets returned.

how to replace part of part of string in javascript

I have two GUIDs. I am looking for to replace c013d94e from 1st guid with cd11d94e of second guid in Javascipt.
I checked javascript replace() method but not sure how i can use it with my specific case.
c013d94e-3210-e511-82ec-303a64efb676 - 1st Guid
cd11d94e-3210-e511-82ec-303a64efb676 - 2nd Guid
Following is my code where i am trying to do it
for(var i=0; i < response[1].length;i++)
angular.forEach($scope.studentPermissions[i][0].Children, function (subject) {
string 1stGuid= response[1].data[i].Id; // it contains cd11d94e-3210-e511-82ec-303a64efb676
subject.Id = // it contains c013d94e-3210-e511-82ec-303a64efb676
});
replace takes 2 parameters, the first is the string to search for and the second is the replacement string. It doesn't modify the original string, it simply returns a new string with the value replaced.
You can perform your replace like this:
var guid = 'c013d94e-3210-e511-82ec-303a64efb676';
guid = guid.replace('c013d94e', 'cd11d94e');
console.log(guid); // 'cd11d94e-3210-e511-82ec-303a64efb676'
#Jamen. Yes the other part of 1st string will always be same. How can i use concatenate?
You don't even need to use replace then? Just make a brand new string:
var guid = "cd11d94e-3210-e511-82ec-303a64efb676";
But, to actually answer the question in the title:
var input = "c013d94e-3210-e511-82ec-303a64efb676";
var output = input.replace("c013d94e", "cd11d94e");
console.log(output); // cd11d94e-3210-e511-82ec-303a64efb676
But like I said, in your situation this shouldn't be necessary, based on the quote.

How to find number string inside delimited string

I've been working on this all day and just cannot seem to figure out why it won't work. I am grabbing a delimited string from a hidden field. I need to test to see if a string is contained in that original string. The simple example below should work but does not.
var orgStr = "091300159|091409568|092005411";
var newArr = orgStr.split('|');
console.log(orgStr);
console.log(newArr);
console.log("inarray? " + $.inArray(newArr, "092005411"));
It seems to work if I can wrap quotes around each value but all attempts are unsuccessful.
In JQuery's inArray function the value needs to come before the array.
console.log("inarray? " + $.inArray("092005411", newArr));
You could also use the native indexOf operator as such:
console.log("inarray? " + newArr.indexOf("092005411"));
Both should output "inarray? 2" to the console.
Have a look at the $.inArray docs.
The first argument is the value and the second the array. You did the opposite.
$.inArray("092005411", newArr) correctly returns 2.

Select text string before comma, set it to uppercase

JS Fiddle Example
OK--I have a field that is a full name (last name, first name). The data that is returning isn't last and first name, it is full name. It is then printed last, first. I want to select just the last name (everything before comma), and set it to uppercase.
I may be mixing jQuery and javascript in my example, I'm not positive--still a newb. However, what I've done in the example is to:
function splitLastName(){
var splitNameArray = $('[data-dojo-attach-point|="physcianNameNode"]').split(",");
var lastName = splitNameArray[0];
var firstName = splitNameArray[1];
lastName.wrap('<span class="isUppercase" />');
}​
Basically, I'm setting a variable of the field--I've tested that it accurately grabs the element I want it to grab. I'm turning the string into an array, split by the comma field. Then setting the two parts of the array as their own variables. Finally, attempting to wrap the lastName string in a span that adds the 'isUppercase' class. I know I'm doing something wrong, what is it?
function splitLastName(){
$('[data-dojo-attach-point|="physcianNameNode"]').html(function(i, v) {
var names = v.split(',');
return '<span class="isUppercase">' +names[0] + '</span>,' + names[1];
});
}
Fiddle
.html() docs
The above is a quick solution setting a new innerHTML to the element. If you want to use proper DOM manipulation, it'd be like:
function splitLastName() {
$('[data-dojo-attach-point|="physcianNameNode"]').each(function() {
var names = $(this).text().split(',');
$(this).empty().append($('<span>', {
'class': 'isUppercase',
text: names[0]
}), ',' + names[1]);
});
}
Fiddle
Note that I'm using .each() so the code above will work regardless of $('[data-dojo-attach-point|="physcianNameNode"]') matching multiple elements or just a single one.
The problem is you are trying to split a JQuery object.
I have updated your example: See here
function splitLastName(){
var element = $('[data-dojo-attach-point|="physcianNameNode"]');//find the element
var html = element.html();//get the contents of the DIV element
var splitNameArray = html.split(",");//Split the value with comma
var lastName = splitNameArray[0];//store the last name
var firstName = splitNameArray[1];//store the first name
var newHtml = '<span class="isUppercase">' + lastName + '</span>, ' + firstName;//create the new html using the parsed values
element.html(newHtml);//assign the new html to the original DIV element (overwriting the old)
}
The problem occurs with this line:
var splitNameArray = $('[data-dojo-attach-point|="physcianNameNode"]').split(",");
The notation:
$('< some name >')
is a jQuery selector that selects an element. If you type this into your console (replacing < some name > with your selector) in your browser you'll see that it returns an object not a string. So your code is trying to split an object. I don't know where the string is located (div, span, input box etc.) but you need to pull the string to do the split. If your string is text in a div or span use:
var splitNameArray = ($('[data-dojo-attach-point|="physcianNameNode"]').text()).split(",");
as this will grab the string contained in that selector and then perform the split on it. Likewise, if it is in an input you will need to use the proper handler to get the value:
var splitNameArray = ($('[data-dojo-attach-point|="physcianNameNode"]').val()).split(",");
This will pull the value from an input and then perform the split. If your string is in html then you could alternatively grab it using the following notation:
var splitNameArray = ($('[data-dojo-attach-point|="physcianNameNode"]').html()).split(",");
This will pull the html and perform the respective split operation.
Hope this helps.

Categories