Double the occurence of character in Javascript - javascript

Input String : abcd
Output String : aabbccdd
How to achieve this using Javascript if 'a' 'b' 'c' 'd' are an elements of an array ..

Simple regex solution:
"abcd".replace(/[\S\s]/g, "$&$&");
Array solution:
"abcd".split("").map(function(x){return x+x}).join("");
For a more generic solution of the string repetition (in the array solution), have a look at Repeat String - Javascript.
Or do it the minimalistic way with loops:
var input = "abcd";
var output = "";
for (var i=0; i<input.length; i++) {
var chr = input.charAt(i);
for (var j=0; j<2; j++)
output += chr;
}

Try this...
var a = "abcd";
var b = "";
for(var i = 0; i < a.length; i++)
b += a.charAt(i) + a.charAt(i);

Related

How to print one word by adding new character on each line in javascript?

I want to do the following:
The string 'London' needs to be printed acording to this logic:
'L'
'Lo'
'Lon'
'Lond'
'Londo'
'London'
An array or loop is what I have in mind, but a can't get it right. Someone who can help?
A simple loop would do it.
Use Array.prototype.slice (https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) to get the wanted portion of the string.
const string = 'London';
for (let i = 0; i < string.length; i++) {
console.log(string.slice(0,i+1));
}
A easy way of using substring method.
const str = "LONDON";
for (let i =0; i<= str.length ;){
console.log(str.substring(0,i++));
}
You may found it strange with using i <= str.length because str.substring(0,0) return empty string "",
You can change to :
const str = "LONDON";
for (let i =0; i< str.length ;){
console.log(str.substring(0,++i));
}
You could use two for loops. One to iterate through all the positions of "London", and the other to iterate through portions of the word "London". Take a look at the code snippet bellow:
var word = "London";
for (var i = 0; i < word.length; i++) {
var str = "";
for (var j = 0; j <= i; j++) {
str += word[j];
}
console.log(str);
}
Below code will be work fine for your problem.
var a = "LONDON";
a = a.split('');
var str = '';
for (var i = 0; i < a.length; i++) {
str += a[i];
console.log(str);
}
Happy Coding!!

For loop isn't looping through the right number of times

I'm trying to print out "w3resource" backwards. Why is the loop ending after 5 times? It works if I change i < stringBecomesArray.length to i < 10.
var string = "w3resource";
var stringBecomesArray = string.split("");
for (var i = 0; i < stringBecomesArray.length; i++){
var newString = [];
newString[i] = stringBecomesArray.pop();
console.log(newString);
}
As someone mentioned in the comments, calling .pop removes the last element on the end of the string, making it shorter.
You probably want to use a while loop, like so:
var str = 'w3resource';
var strArr = str.split('');
var newStr = '';
while (strArr.length > 0){
newStr += strArr.pop();
}
console.log(newStr);
Also, you don't need to use .split, you can access a string like an array. Using a for loop and reversed iteration you can do it like so:
var str = 'w3resource';
var newStr = '';
var i;
for (i = str.length - 1; i >= 0; i--){
newStr += str[i]
}
console.log(newStr);
The best way to do this it to actually go backwards though the word:
var string = "w3resource";
var newString = "";
for (var i = string.length; i > 0; i--){
newString += string[i];
}
console.log(newString);

looping through an array and for each item capturing string before '-' and re constructing a new array

This might be very simple and I am missing something obvious
I am only concerned with what ever I have before the '_' in the array items and create a new array out of that. Here is how I am trying to do this
var x = ['P0000004_604990244255', 'P11100012_604990244823', 'P0002346722_604990112823'];
//x_trim = ['P0000004', 'P11100012', 'P0002346722']; this is how the new array should look like
var x_trim = '[';
for(var i = 0; i<= x.length; x++){
x_trim += '"' + x[i].split('_')[0] + '",';
}
x_trim += ']';
x_trim = x_trim.substring(0, x_trim.length - 2)+ ']';
x_trim = eval(x_trim);
console.log(x_trim)
It is only returning the first item of the array in the correct format. I am not able to iterate through the array. Or is there a better way of doing this? It has to pure javascript..no jQuery
Try this
var x = ['P0000004_604990244255', 'P11100012_604990244823', 'P0002346722_604990112823'];
var arr = [];
for(var i=0;i<x.length; i++)arr[i] = x[i].split("_")[0];
Your for loop is wrong,. It should look like
for(var i=0; i<x.length; i++)
You should do i++ instead of x++ and i should stop just before x.length instead of at <= (due to 0-based indexing)
You can just use substring() and indexOf(), no need to split() anything. It comes out with much simpler and cleaner looking code:
var x = [ 'P0000004_604990244255',
'P11100012_604990244823',
'P0002346722_604990112823' ];
var y = [];
for (var i = 0; i < x.length; i++) {
var s = x[i];
y.push(s.substring(0, s.indexOf('_')));
}
console.log(y);
// logs
// ["P0000004", "P11100012", "P0002346722"]

splitting a string based on delimiter using javascript

Hi I'm trying to split a string based on multiple delimiters.Below is the code
var data="- This, a sample string.";
var delimiters=[" ",".","-",","];
var myArray = new Array();
for(var i=0;i<delimiters.length;i++)
{
if(myArray == ''){
myArray = data.split(delimiters[i])
}
else
{
for(var j=0;j<myArray.length;j++){
var tempArray = myArray[j].split(delimiters[i]);
if(tempArray.length != 1){
myArray.splice(j,1);
var myArray = myArray.concat(tempArray);
}
}
}
}
console.log("info","String split using delimiters is - "+ myArray);
Below is the output that i get
a,sample,string,,,,This,
The output that i should get is
This
a
sample
string
I'm stuck here dont know where i am going wrong.Any help will be much appreciated.
You could pass a regexp into data.split() as described here.
I'm not great with regexp but in this case something like this would work:
var tempArr = [];
myArray = data.split(/,|-| |\./);
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] !== "") {
tempArr.push(myArray[i]);
}
}
myArray = tempArr;
console.log(myArray);
I'm sure there's probably a way to discard empty strings from the array in the regexp without needing a loop but I don't know it - hopefully a helpful start though.
Here you go:
var data = ["- This, a sample string."];
var delimiters=[" ",".","-",","];
for (var i=0; i < delimiters.length; i++) {
var tmpArr = [];
for (var j = 0; j < data.length; j++) {
var parts = data[j].split(delimiters[i]);
for (var k = 0; k < parts.length; k++) {
if (parts[k]) {
tmpArr.push(parts[k]);
}
};
}
data = tmpArr;
}
console.log("info","String split using delimiters is - ", data);
Check for string length > 0 before doing a concat , and not != 1.
Zero length strings are getting appended to your array.

Remove prefix from a list of strings

How can I remove a sub-string (a prefix) from a array of string elements? (remove the sub string from each element)
Using RegExp and ^ to ensure it is the prefix and not just somewhere in the string:
var arr = ['a1', 'a2', 'a54a'];
for(var i = 0, len = arr.length; i < len; i++) {
arr[i] = arr[i].replace(/^a/, '');
}
arr; // '1,2,54a' removing the 'a' at the begining
function trimPrefix(str, prefix) {
if (str.startsWith(prefix)) {
return str.slice(prefix.length)
} else {
return str
}
}
var prefix = "DynamicPrefix"
trimPrefix("DynamicPrefix other content", prefix)
Many of the answers already given are wrong, because they'll remove the target string from anywhere in each of the elements (not just the beginning). Here's another approach:
var str = "str_";
["str_one", "str_two_str_", "str_three"].map(function(el) {
return el.replace(new RegExp("^" + str), '');
});
Result:
["one", "two_str_", "three"]
Or, if you prefer simple iteration (with no higher-order function):
var str = "str_";
var list = ["str_one", "str_two_str_", "str_three"];
for (var i = 0; i < list.length; i++)
list[i] = list[i].replace(new RegExp("^" + str), '');
var pre = 'prefix_';
my_arr = my_arr.map(function(v){ return v.slice(pre.length); });
See MDN if full browser support for .map() is needed.
you can also use .forEach() if you need to keep the original array.
var pre = 'prefix_';
my_arr.forEach(function(v,i){ my_arr[i] = v.slice(pre.length); });
var i;
for(i = 0; i < arr.length; i++)
arr[i] = arr[i].replace(substr, '');
Example:
var arr = ['test1', '2test', '3test3'];
// Use only one of these lines
var substr = 'test'; // This is for substrings
var substr = /^test/; // This is for prefixes only
var i;
for(i = 0; i < arr.length; i++)
arr[i] = arr[i].replace(substr, '');
console.log(arr); // Prints ["1", "2", "33"] to console
Just for some variety:
substr = new RegExp('(^|\|)prefix_', 'g');
arr = arr.join('|').replace(substr, '').split('|')
edit - to show how you can limit to just the prefix with the right regexp.
Just iterate on your list of string (with a for loop for example) and use the replace method (details here)
Simply loop through them?
var list = ["foo", "bar", "meh"];
for(var i = 0; i < list.length; i++)
list[i] = list[i].substr(1, 1);
http://jsfiddle.net/DcvE2/1/
You could use the jQuery map function -
var arr = $.map(['a1', 'a2'],function (s) {
return s.replace(/^a/,'');
});
I would do this:
var element = document.getElementsByTagName('p');
for(i in element){
str = element[i].innerHTML;
str = str.replace(/^pre_/,'');
element[i].innerHTML = str;
}

Categories

Resources