Javascript: Split string by loop in loop - javascript

I've got string with IDs and Names separated by ^ (between ID and Names) and ; (between sets) for example
var string = "1^John Smith;2^Sophia Williams;3^Emily Johnson;";
I need to get something like this
$('#1').html('<option value="1">John Smith</option><option value="2">Sophia Williams</option><option value="3">Emily Johnson</option>');
I tried loops but got stuck:
var string = "1^John Smith;2^Sophia Williams;3^Emily Johnson;";
var a = string.split(";"),
i;
for (i = 0; i < a.length; i++){
if (a[i] !== ""){
var b = a[i].split("^"),
i2;
for (var i2 = 0; i2 < b.length; i++) {
var name = b[i2];
console.log(name);
}
}
}
Im not sure that it's good way

Using Option()
new Option(text, value, defaultSelected, selected)
var string = "1^John Smith;2^Sophia Williams;3^Emily Johnson;"
var options = string.split(';').map(i => {
return new Option(...i.split('^').reverse())
})
$('#1').html(options)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="1"></select>

You can build a HTML string inside your loop by grabbing the first element from b as the value for your option and the second element from b to be the text in your option tag. You can then add a string HTML version of the option tag using these text and value components to the accumulated string each iteration of your for-loop:
var string = "1^John Smith;2^Sophia Williams;3^Emily Johnson;";
var a = string.split(";");
var html_str = "";
for (var i = 0; i < a.length-1; i++) { // loop to a.length-1 so you don't need an if-statement to check blanks
var b = a[i].split("^");
var val = b[0];
var txt = b[1];
html_str += '<option value="' + val +'">' + txt +'</option>';
}
$('#one').html(html_str);
console.log(html_str);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="one"></select>
An alternative approach could be to use a regular expression to get the components from your string an convert it to your desired HTML string by using .replace() with a replacement function:
var string = "1^John Smith;2^Sophia Williams;3^Emily Johnson;";
var html_str = string.replace(/(\d+)\^([^;]+);/g, (_, val, txt) => `<option value="${val}">${txt}</option>`);
$('#one').html(html_str);
console.log(html_str);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="one">
</select>
The above regular expression:
(\d+)\^: Groups any digits (group 1) which have a carat ^ following them
([^;]+);: Groups any characters which are not a semi-colon ; (group 2), which are followed by a semi-colon.
These groups are formed for each occurrence in your string, and then used in the .replace() method's callback, where group 1 is val and group 2 is txt.

Related

Swap columns in a one-dimensional array in Javascript

I'm trying to swap 2 columns from a delimited text, but the farthest I got is grabbing the first column. This is what I'm trying to achieve.
// Input
A1—B1—C1
A2—B2—C2
A3—B3—C3
Swap column #1 with column #3. Delimiter is "—".
// Result
C1—B1—A1
C2—B2—A2
C3—B3—A3
JSFiddle
var text = $('#input').val().split("\n");
var delimiter = "—";
var col_1 = $('#col_1').val() - 1;
var col_2 = $('#col_2').val() - 1;
var out = [];
var col_arr = [];
var col = '';
// Get first column
for (var i = 0; i < text.length; i++) {
col_arr = text[i].split(delimiter);
col = col_arr[col_1];
if (col != undefined) col = col;
else col = '';
out[i] = col;
}
text = out.join('\n');
You've successfully split the text into an array of its constituent parts using split, you can now use the reverse Array function to reverse the order, and then rejoin all the parts together using the join Array function and your delimiter.
This simplifies your code in your for loop to this:
for (var i = 0; i < text.length; i++) {
out[i] = text[i].split(delimiter).reverse().join(delimiter);
}
It's a simple swap with a temp variable. I've used Array.map() to iterate the text array, but you can replace it with a `for...loop.
$("button").click(function() {
var delimiter = "—";
var rowDelimiter = "\n";
var text = $('#input').val()
.trim() // remove white space before and after the text
.split(rowDelimiter);
var col_1 = $('#col_1').val() - 1;
var col_2 = $('#col_2').val() - 1;
// check the cols to be a number between 0 and the amount of columns
// and notify user if their not
var result = text.map(function(row) {
var arr = row.split(delimiter);
var temp = arr[col_1]; // cache the value of col_1
arr[col_1] = arr[col_2]; // set the value of col_2 1 to be that of column 2
arr[col_2] = temp; // set the value of col_2 to be the value of temp
return arr.join(delimiter);
}).join(rowDelimiter);
$('#output').val(result);
});
textarea {
width: 100%;
height: 120px
}
button {
margin: 10px 0
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Swap col #<input id="col_1" value="2"> with col #<input id="col_2" value="3">
<br>
<textarea id="input">
A1—B1—C1—D1
A2—B2—C2—D2
A3—B3—C3—D3
</textarea>
<button>Swap</button>
<textarea id="output">
</textarea>
split() returns an array, so what you can do is first processing your text data to an actual array so its easier to work on it :
function getArrayFromInput(){
var arr = [];
var lines = $('#input').val().split("\n");
for (let line of lines){
let column = line.split('—');
arr.push(column);
}
return arr;
}
//returns [['A1','B1','C1'],['A2','B2','C2'],['A3','B3','C3']]
It'll be easier to do what you're trying to do then :)
function swapColumns(inputArr, col1, col2){
var arr = JSON.parse(JSON.stringify(inputArr)); //get inputArr structure
for(let i = 0; i<arr.length; i++){
//swap the values
arr[i][col1] = inputArr[i][col2];
arr[i][col2] = inputArr[i][col1];
}
return arr;
}
//return your array with swaped columns
I'll then let you handle the array to text conversion !
Feel free to ask any question

Is it possible to generate all the emojis and append to the select dropdown?

Is there any possible ways to generate all the emojis and append them in to a single select dropdown by using JavaScript? Or I have to type each of them manually?
<select>
<option>🍰</option>
<option>🐲</option>
<select>
<script>
function()
{
// How do I put all the emojis into the select dropdown..?
}
</script>
You can define start and end values of different emoji ranges. Then, you can loop through each range and append emoji to option tag.
var mySelect = document.getElementById('mySelect')
var newOption;
var emojRange = [
[128513, 128591], [9986, 10160], [128640, 128704]
];
//inside emojRange 2d array , define range arrays (start number,end number).
//1st array : Emoticons icons
//2nd range : Dingbats.
//3rd range : Transport and map symbols
for (var i = 0; i < emojRange.length; i++) {
var range = emojRange[i];
for (var x = range[0]; x < range[1]; x++) {
newOption = document.createElement('option');
newOption.value = x;
newOption.innerHTML = "&#" + x + ";";
mySelect.appendChild(newOption);
}
}
I took hexadecimal ranges from this site: http://apps.timwhitlock.info/emoji/tables/unicode.
var mySelect = document.getElementById('mySelect')
var newOption;
var emojRange = [
[128513, 128591] ,[9986,10160],[128640,128704]
];
//inside array define range arrays.
//1st array : Emoticons icons
//2nd range : Dingbats.
//3rd range : Transport and map symbols
for (var i = 0; i < emojRange.length; i++) {
var range = emojRange[i];
for (var x = range[0]; x < range[1]; x++) {
newOption = document.createElement('option');
newOption.value = x;
newOption.innerHTML = "&#" + x + ";";
mySelect.appendChild(newOption);
}
}
option {
font-size:50px;
}
<select id="mySelect">
</select>
I downloaded the characters from Full Emoji Data, v3.0 and put them in a JavaScript library hosted in Github, released under the unlicense.
Using that you can write code as follows:
var target = document.getElementById("target");
var emojiCount = emoji.length;
for(var index = 0; index < emojiCount; index++)
{
addEmoji(emoji[index]);
}
function addEmoji(code)
{
var option = document.createElement('option');
option.innerHTML = code;
target.appendChild(option);
}
<script src="https://rawgit.com/theraot/emoji/master/emoji.js" charset="utf-8"></script>
<select id ="target">
<select>
You could use JavaScript to filter the list to only those emoji that don't have a modifier.
I'll copy the README I wrote for the project in Github below:
Emoji
List of all emoji for JavaScript
Use as follows:
<script src="https://rawgit.com/theraot/emoji/master/emoji.js" charset="utf-8"></script>
The list of emoji was retrieved from Full Emoji Data, v3.0
Note 1: Some emoji are composed of two Unicode characters. These are using emoji modifiers and may not render correctly.
Note 2: Support may vary from browser to browser and platform to platform, the use of a emoji font is advised.
If your emojis are unicode characters, put all of them in an array and loop through to construct your select dropdown as shown below :
var myEmojis = ['&#9786', '&#9785']; //put all your emojis in this array
var selectOptions = "<option>select</option>";
for(var i = 0; i < myEmojis.length; i++){
selectOptions += "<option>" + myEmojis[i] + "</option>"
}
$('select').html(selectOptions);

swap letters with numeric , using javascript search

I'm a beginner in JavaScript, a self-learner using free pdf books, google and Stackoverflow.
I am stuck in a self assigned task ...
Swapping words with numeric digits, taking values from one text-box, performing swapping and putting result in another text-box. For example when I type six svn zro the output must be 670
But when I type something in textBox1 the result in textbox2 is "Undefined"**
Please debug it only using simple JavaScript, not jQuery.
Here is my code...
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function myFunction()
{
var a = ["one","two","tri","for","fiv","six","svn","egt","nin","zro"];
var b = [1,2,3,4,5,6,7,8,9,0];
var str = document.getElementById("textBox1").value;
var x = document.getElementById("textBox2").value;
var len = str.length;
for (var k=0; k < 200; k++)
{
var n = str.search(new RegExp(a[k], "i"));
var str1 = str.substring(0, n) + b[k] + str.substring(n+3, len);
document.getElementById('textBox2').value = str1.toString();
};
}
</script>
</head>
<body>
<input type="text" onkeyup="myFunction();" id="textBox1" autofocus/>
<br><br><br><br><br><br>
<input type="text" id="textBox2" />
</body>
</html>
The reason you get undefined is still because of the for loop.
When k reaches 10, a[10] does not exist and so returns undefined. This gets used as the replacement value in your string.
If you restrict k to the length of array a, you will not get undefined values.
The other issue is that you are always starting from the original string, so previous replacements are ignored. You need to always use str and not have str1.
Finally it is simpler to just use the replace() function rather than working out substrings - I tried to reuse your substring code but couldn't get it working.
So your function can become:
function myFunction() {
// values to search for - these can be strings or a regex string
var a = ["zro", "one", "two", "tri", "for", "fiv", "six", "svn", "egt", "nin"];
// get the input value
// we will perform all replacements against this
var str = document.getElementById("textBox1").value;
// loop through the array and replace each value in "str" with its index
// note we are reusing "str" each time to keep the previous replacements intact
// replace() can take either a string or a regex
for (var k = 0; k < a.length; k++) {
// put "zro" at the start of "a" so "k" is now the same as b[k] - no need for "b"
// create a RegExp from the string, set it to global replace (g) so it works if there is more than one match in the string, and case insensitive (i) in case they type "One"
str = str.replace(new RegExp(a[k], "gi"), k);
};
// store final value in the other textbox
document.getElementById('textBox2').value = str;
}
<input type="text" onkeyup="myFunction();" id="textBox1" autofocus="autofocus" />
<br/>
<input type="text" id="textBox2" />
EDIT/footnote: replace() is still simpler but you can use substring() - the problem with your original code is that if the regex does not match anything, n will be -1 and mess up str. So you need to check if n > -1 before you do the substring part:
for (var k = 0; k < a.length; k++) {
var n = str.search(new RegExp(a[k], "i"));
if(n > -1) {
// n+a[k].length is better than n+3, in case a[k] isn't 3 chars!
str = str.substring(0, n) + k + str.substring(n+a[k].length, str.length);
}
};
Here is my suggestion
function myFunction() {
var a = ["zro","one","two","tri","for","fiv","six","svn","egt","nin"]; // 0-based
var str = document.getElementById("textBox1").value;
var words = str.split(" "),len=words.length, str1=""; // split on words
for (var i=0; i < len; i++) { // run over length of array
var idx = a.indexOf(words[i]); // find the word in the index array
if (idx !=-1) str1+=idx;
}
if (str1) document.getElementById('textBox2').value=str1;
}
<input type="text" onkeyup="myFunction();" id="textBox1" autofocus/>
<br><br><br><br><br><br>
<input type="text" id="textBox2" />
If you want to have any entry containing any of the a[] strings, then this will do it
function myFunction1() {
var str = document.getElementById("textBox1").value;
var a = ["zro","one","two","tri","for","fiv","six","svn","egt","nin"];
var len = a.length;
for (var i=0; i < len; i++) {
var idx = str.indexOf(a[i]); // or str.toUpperCase().indexOf(a[i].toUpperCase())
if (idx !=-1) str = str.split(a[i]).join(i); // or use substr if case insensitive
}
if (str) document.getElementById('textBox2').value=str;
}

translate a variable amount of input values into a select

var namelist = editnamebox.children.value;
for (var f = 0; f < namelist.length; f += 1) {
slotname.innerHTML = '<optgroup><option>' + namelist[f] + '</option></optgroup>';
}
editnamebox is a div containing avariable number of inputs I want to generate a with the value of each editnamebox input as an option.
The code above does no work, I also tried namelist[f].value instead of in the namelist var which also does not run. What is wrong here?
Full page: http://powerpoint.azurewebsites.net/
Set a timeslot. "Undefined" should be the content of the empty text fields above
You should build the string with the loop and then update the innerHTML. (Assuming other portions are correct without seeing your markup)
var namelist = editnamebox.children,
slotnameHtml = '';
//build html string
for (var f = 0; f < namelist.length; f += 1) {
slotnameHtml += '<optgroup><option>'
+ namelist[f].value
+ '</option></optgroup>';
}
slotname.innerHTML = slotnameHtml; //update html

Remove comma from javascript array

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("").

Categories