Insert string into string on a dynamic position [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a string that includes some color tags, that looks like this:
[GREEN][BLUE][RED]
The position of the tags can be different. So [GREEN] could be in middle or in the last position as well.
Now I have a new color tag that should be added to that list, let's call it [YELLOW]. So [YELLOW] has a dynamic position number, let's take the variable const position = 2. Well, that means that [YELLOW] should be placed in second place, which should look like this:
[GREEN][YELLOW][BLUE][RED]
How can I do this?

const text = "[GREEN][BLUE][RED]";
const inputNumber = 2;
const addingText = "[YELLOW]";
const index = text.split("[", inputNumber).join("[").length;
const output = [text.slice(0, index), addingText, text.slice(index)].join('');
console.log(output)

I would have an array of placeholders like this:
const placeholders = ['[GREEN]', '[YELLOW]', '[BLUE]', '[RED]'];
When you need to add another placeholder in a certain position you simply use the splice function:
placeholder.splice(position, 0, newPlaceholder);
Then when you need to use it, you just convert it to a string:
placeholder.join('');
I think this would make it much easier to handle, more readable and possibly quicker too.

You could use .replace function with the following regex.
((?:\[.*?\]){2})
When you insert variable to regex using${variable}, you use:
((?:\\[.*?\\]){${position-1}})
var listColors = "[GREEN][BLUE][RED]";
const position = 2;
var color = "[YELLOW]";
var pattern = `((?:\\[.*?\\]){${position-1}})`;
var regex = new RegExp(pattern);
var newListColors = listColors.replace(regex, `$1${color}`);
console.log(newListColors);

I would split this to array and then add at specific position:
var text = "[GREEN][BLUE][RED]";
var matches = text.match(/\[\w+\]/g);
matches.splice(1, 0, "[YELLOW]");
var result = matches.join("")
console.log(result);
https://www.w3schools.com/jsref/jsref_splice.asp

You should find in which possition the first ] appears and then concat the [yellow]

Related

Javascript array with values [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
The below code is a javascript interview question. I should get the output as [5,1,2,3,4]. Anyone can help me out this.
const input = [1,2,3,4,5]
const n = 4;
var output = []
console.log(output)
Without modifying the input array:
const input = [1,2,3,4,5]
const n = 4;
var output = []
output= [input[n],input.slice(0,n)].flat()
console.log(output)
From my understanding, the question is that when 'n' is a given index, you should be able to remove the element from the index n of the array and insert it at the very beginning of the array. As arrays are 0 based, it means that if n=4, then the element at nth index is 5 as per the given array.
In order to do that, you can do the following:
Use the splice method on the nth index and pass 1 as 2nd parameter, so you only remove the element at nth index.
Then use the unshift method on input to remove add the nth element at the beginning of the array. Unshift returns the length of the array, but you want the entire array to be stored in output.
So, you store the input array in the output variable.
Please run the below snippet for a better understanding. Let me know if my understanding of your question is not correct, so I can update my answer accordingly.
const input = [1,2,3,4,5]
const n = 4;
const [el] = input.splice(n,1); //array destructuring
input.unshift(el);
const output = input;
console.log(output)
const input = [1,2,3,4,5]
const n = 4
input.splice(0, 0, input[n])
input.splice(n+1, 1)
var output = [...input]
console.log(output)

How to do array from the string ? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have an adress such as https://stackoverflow.com/#/schedulePage/some/another , how can I make it to an array with elements after # ?
var urlToSplit = "https://stackoverflow.com/#/schedulePage/some/another"
var onlyAfterHash = urlToSplit.split("/#/")[1];
var result = onlyAfterHash.split("/");
console.log(result);
Use the split function
var str = "https://stackoverflow.com/#/schedulePage/some/another";
var res = str.split("#");
I think you just want something like this.First here I just split out the string by #, grab the second part of split result i.e index 1 then again splitting the result with / and finally filter out the empty string from the generated array.
var string = 'https://stackoverflow.com/#/schedulePage/some/another';
var result = string.split('#')[1].split('/');
var filtered = result.filter((entry)=>entry.trim() != '');
console.log(filtered);

fetch first element of every string in array using javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have an array like :
["ds","1:0,1,2,3,4","2:0,2,3,4,5","3:0,6,7,8,9"]
I want to fetch elements such that it has:
[1:0,2:0,3:0] (only the first element of every string in array leaving the ds element)
Please suggest a solution in JavaScript.
Use a forEach to loop through the array and split using ','.
var arr = ["ds", "1:0,1,2,3,4", "2:0,2,3,4,5", "3:0,6,7,8,9"];
var newArr = [];
arr.forEach(function(el,index) {
if(index!=0)
newArr.push(el.split(',')[0]);
});
console.log(newArr)
You can use the array .reduce() method:
var input = ["ds","1:0,1,2,3,4","2:0,2,3,4,5","3:0,6,7,8,9"]
var output = input.reduce(function(acc, str) {
var val = str.match(/^\d+:\d+/)
if (val) acc.push(val[0])
return acc
}, [])
console.log(output)
When processing each element you could say if (str != "ds") or skip the first element based on its index, and then use str.split(",")[0] or some combination of .slice() or .substr() and .indexOf() or whatever, but I've chosen to use a regex /^\d+:\d+/ with the .match() method to check if each input element contains the digits:digits structure at the beginning - that way it really doesn't matter what order the elements are in or what other arbitrary values might exist, it only uses elements that match the required pattern.
var arr = ["ds","1:0,1,2,3,4","2:0,2,3,4,5","3:0,6,7,8,9"];
var newArr = arr.slice(1, arr.length).map(function (el) {
return el.split(',')[0];
});
console.log(newArr);
var newarray = [];
oldarray.splice(0,1);
oldarray.forEach(function (element) {
newarray.push(element.split(",")[0]);
});

Convert word list into array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've tried to see if there were any scripts to convert a list of words into an array and I can't seem to find one.
Anyone know where I can find one?
Input:
Dog
Cat
Hamster
Gets converted to
["Dog", "Cat", "Hamster"]
Noo.. this isn't what I mean. I have a txt file with a bunch of words on each line and I was wondering if there was something out there already created that can convert each word into an array.
Just use split on the string.
For example:
var textarea = document.getElementById('list');
var arr = [];
textarea.addEventListener('input', function () {
arr = this.value.split('\n');
console.log(arr);
}, false);
Demo
If the string is actually "Dog\nCat\nHamster" then just do
"Dog\nCat\nHamster".split('\n');//returns ["Dog", "Cat", "Hamster"]
For a TextArea try this
myTextArea.value.split('\n'); // it will return desired output.
Where myTextArea is the TextArea you can get using getElement.
I think the best solution for a textarea input is using the match() function of javascript like this:
var words = []
$('textarea').on('blur', function(){
words = $(this).val().match(/\w+/g)
alert(words)
})
here a fiddle of it working.
This doesn't need for the words to be in different lines.

improving my Javascript code: set a style of a link in page nav bar [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
a javascript+DOM question.
Can someone improve my code?
I have a page nav bar like this (on some pages):
<div id="pagebar">
1
2
3
4
5
6
</div>
I want my javascript to change the link style so that the style of the current page is highlighted.
My javascript code is this. It finds the current page's url, then try to match it with one of the link tag. If match, then set style.
function setPageBarStyle() {
var pageNavBar = document.getElementById("pagebar");
if (pageNavBar != null) {
var fPath = document.location.pathname;
var fPathParts = fPath.split('/');
var fName = (fPathParts[fPathParts.length-1]); // file name after last slash. e.g. xyz.html
var linkTags = pageNavBar.getElementsByTagName("a");
for (var ii = 0; ii < linkTags.length; ii++) {
var aUrl = linkTags[ii].href;
var aUrlParts = aUrl.split("/");
var aUrlLastPart = (aUrlParts[aUrlParts.length-1]); // part after last slash. e.g. xyz.html
if (aUrlLastPart == fName) {
linkTags[ii].style.border="thin solid blue";
}
}
}
}
setPageBarStyle();
How can i improve the code? I am new to DOM scripting.
The way i split the path seem too verbose, with many variables. I think it can be done with regex, but don't know how with javascript/DOM.
Thanks.
You can change this:
var aUrl = linkTags[ii].href;
var aUrlParts = aUrl.split("/");
var aUrlLastPart = (aUrlParts[aUrlParts.length-1]); // part before last slash. e.g. xyz.html
With this:
var aUrlLastPart = linkTags[ii].href.split("/").pop();
The Pop() method will return the last element of the array returned by split() and remove it from the array (which in your case, is irrelevant).
I would also recommend checking out jQuery or similars, in order to manage cross browser JS easier...
Let me know if it helps! :)

Categories

Resources