Convert char to String in Javascript - javascript

Read it, Before it gets marked as duplicate
Sorry! I couldn't come up with a better description of the question
Anyways, I was making a simple program which reverses the given word (e.g 'word' to 'drow'). I was trying to convert the String into char array first and then printing each character backwards in the console using for loop. However, I need to save the value in a String now that I can't seem to figure out.
This is the code here:
var answer = document.getElementById("ta").value;
var arr = answer.split("");
for(i=arr.length-1;i>=0;i--) { //minus 1 because index starts at 0
str = arr[i];
console.log(str); //it works but displays each character individually
}
I just want all the characters in a String. Please help! Brevity in the answer would be appreciated

JavaScript unlike other oops, provide an inherited reverse function that reverses array. So one answer to this whould be:
let arr = answer.split("") //note this creates an array with each char as element of array
arr = arr.reverse(); //this reverses the array
let string = arr.join(""); //this joins the array into a single string
Another method would be the one you are trying to do, create your own reverse function. You are doing it all right but just missing a step, that is to join the array, you are simply printing each letter of the array and thats the property of console.log that each console.log prints to a new line. That explains why you are getting it all in new line.
var answer = document.getElementById("ta").value;
var arr = answer.split("");
var str ="";
for(i=arr.length-1;i>=0;i--) { //minus 1 because index starts at 0
str =str + arr[i];
}
console.log(str); //it should be outside the loop and print string once it has been formed
P.S:I have given as much detail I can on this to get you started but this is a very basic question and doesnt deserve to be here, you should follow some basic concepts of js on mdn or w3schools. Plus google your problems before turning to stackoverflow.

If you want to put all the characters in str you can try this way:
str= str+arr[i]
or try this way:
var str = "";
arr.forEach(element => {str= str+element});
console.log(str)

Related

search text in array using regex in javascript

I am very new to making search text in array some elements in array are in rangers i.e it cant be anything after certain text in this AA and A regex and I have multi-dimensional array and I want search text in each array . So I wrote something like this.I put AA* in array so only first 2 character should match and A* for only one character match.
arr = [
["AA*","ABC","XYZ"] ,
["A*","AXY","AAJ"]
]
var text = "AA3";
for ($i=0; $i<arr.length; $i++ ){
var new_array = [];
new_array = arr[$i];
new_array.filter(function(array_element) {
var result = new RegExp(array_element).test(text);
if( result == true){
console.log(arr[$i]);
}
});
}
So what i want is when text = "AA3" or anything after double A AA[anything] and the output should be first array which is ["AA*","ABC","XYZ"] but I am getting both array as output and when text = "A3" then output should be second array which is ["A*","POI","LKJ"] but I am getting both array.But if text = "ABC" or text = "AAJ" then it should output first array or second array respectively.I dont know anything about how to write regex or is there anyway I can implement this using any other method.
Thanks in advance any advice will be helpful.
Summary
In short, the issue is "*"! The * found in the members of the set array is why you're getting the same array each time.
Detailed Info
Regexp is a one concept most developers find hard to understand (I am one of such btw 😅).
I'll start off with an excerpt intro to Regexp on MDN
Regexp are patterns used to match character combinations in strings - MDN
With that in mind you want to understand what goes on with your code.
When you create a Regex like /A*/ to test "AA3", what would be matched would be A, AA, etc. This is a truthy in javascript. You would want a more stricter matching with ^ or $ or strictly matching a number with \d.
I rewrote your code as a function below:
arr = [
["AA*", "ABC", "XYZ"],
["A*", "AXY", "AAJ"],
];
findInArray(arr, "AA3") // prints both array
findInArray(arr, "AAJ") // prints second array
findInArray(arr, "ABC") // prints first array
function findInArray(array, value) {
return array.filter((subArray) =>
subArray.some((item) => {
const check = new RegExp(value);
return check.test(item);
})
);
}
Problem
The problem lies in the fact you use each of the strings as a regex.
For a string with a * wildcard, this evaluates to zero or more matches of the immediately preceding item, which will always be true.
For a string consisting solely of alphanumerics, this is comparing a string to itself, which similarly will always give true.
For strings containing characters that constitute the regex's syntax definition, this could result in errors or unintended behavior.
MDN article on RegExp quantifiers
Rewrite
Assumptions:
The value with a * wildcard is always only at the 0th position,
There is only one such wildcard in its string,
The question mentions that for text = 'AAJ' only the 2nd array shall be returned, but both the AA* from the 1st array and AAJ from the 2nd would seem to match this text.
As such, I assume the wildcard can only stand for a number (as other examples seem to suggest).
Code:
const abc = (arrs, text) => {
return arrs.filter(arr => {
const regex = new RegExp(`^${arr[0].replace('*', '\\d+')}$`);
return regex.test(text) || arr.includes(text);
})
}
const arr = [
["AA*", "ABC", "XYZ"],
["A*", "AXY", "AAJ"]
];
console.log(
`1=[${abc(arr, "AA3")}]
2=[${abc(arr, "ABC")}]
3=[${abc(arr, "AAJ")}]`);

How to remove strings before nth character in a text?

I have a dynamically generated text like this
xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0
How can I remove everything before Map ...? I know there is a hard coded way to do this by using substring() but as I said these strings are dynamic and before Map .. can change so I need to do this dynamically by removing everything before 4th index of - character.
You could remove all four minuses and the characters between from start of the string.
var string = 'xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0',
stripped = string.replace(/^([^-]*-){4}/, '');
console.log(stripped);
I would just find the index of Map and use it to slice the string:
let str = "xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0"
let ind = str.indexOf("Map")
console.log(str.slice(ind))
If you prefer a regex (or you may have occurrences of Map in the prefix) you man match exactly what you want with:
let str = "xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0"
let arr = str.match(/^(?:.+?-){4}(.*)/)
console.log(arr[1])
I would just split on the word Map and take the first index
var splitUp = 'xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0'.split('Map')
var firstPart = splitUp[0]
Uses String.replace with regex expression should be the popular solution.
Based on the OP states: so I need to do this dynamically by removing everything before 4th index of - character.,
I think another solution is split('-') first, then join the strings after 4th -.
let test = 'xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0'
console.log(test.split('-').slice(4).join('-'))

Why is JavaScript's split() method not splitting on ":"?

So to start off, a bit of context. I am pulling data from the following url: "https://webster.cs.washington.edu/pokedex/pokedex.php?pokedex=all" using a GET method. The data returned is a series of Pokemon names and image names in the following format.
Name1:name1.png
Name2:name2.png
...
The list is 151 items long. When I call the typeOf() method "String" is returned, so I am fairly certain it is a String I am dealing with here. What I would like to do is split the String on the delimiters of "\n" and ":".
What I would like:
Name1,name1.png,Name2,name2.png...
After some experimentation with Regex, I found that the Regex to do this was "\n|:". Using this I wrote the following line to split the String apart. I tested this Regex on https://regex101.com and it seems to work properly there.
var splitData = data.split("\n|:");
("data" is the String I receive from the url.)
But instead of splitting the String and placing the substrings into an array it doesn't do anything. (At least as far as I can see.) As such my next idea was to try replacing the characters that were giving me trouble with another character and then splitting on that new character.
data = data.replace("\n", " ");
data = data.replace("/:/g", " ");
var splitData = data.split(" ");
The first line that replaces new line characters does work, but the second line to replace the ":" does not seem to do anything. So I end up with an array that is filled with Strings that look like this.
Name1:name1.png
I can split these strings by calling their index and then splitting the substring stored within, which only confuses me more.
data = data.replace("\n", " ");
var splitData = data.split(" ");
alert(splitData[0].split(":")[1]);
The above code returns "name1.png".
Am I missing something regarding the split() method? Is my Regex wrong? Is there a better way to achieve what I am attempting to do?
Right now you are splitting on the string literal "\n|:" but to do a regex you want data.split(/[:\n]/)
The MDN page shows two ways to build a Regex:
var regex1 = /\w+/;
var regex2 = new RegExp('\\w+');
The following test script was able to work for me. I decided to use the regex in the split instead of trying to replace tokens in the string. It seemed to do the trick for me.
let testResponse = `Abra:abra.png
Aerodactyl:aerodactyl.png`;
let dataArray = testResponse.split(/\n|:/g);
let commaSeperated = dataArray.join(',');
console.log(commaSeperated);
So you can simply use regex by excluding the quotes all together.
You can look at the documentation here for regular expressions. They give the following examples:
var re = /ab+c/;
var re = new RegExp('ab+c');
See below for your expected output:
var data = `Name1:name1.png
Name2:name2.png`;
var splitData = data.split(/[\n:]/);
console.log(splitData);
//Join them by a comma to get all results
console.log(splitData.join(','));
//For some nice key value pairs, you can reduce the array into an object:
var kvps = data.split("\n").reduce((res, line) => {
var split = line.split(':');
return {
...res,
[split[0]]: split[1]
};
}, {});
console.log(kvps);
I tried and this works good.
str.split(/[:\n]/)
Here is a plunker.
plunker

Program a JavaScript loop to take out characters

Suppose I've this code:
XBGa_AHjhdjsDjk_sad/safasdf_Sdfsdfasfdsa
I want to take XBGa_AHjhdjsDjk_sad out of this. I want to run a loop in JavaScript which appends each character to a variable and if the character is / the loop is terminated.
How do I do that?
var str = 'XBGa_AHjhdjsDjk_sad/safasdf_Sdfsdfasfdsa';
var spl = str.split('/');
var result = spl[0]; // This will be equal to XBGa_AHjhdjsDjk_sad
I am not sure if you mean that you want the first or second part of the string, but you get the idea. spl becomes an array after executing the split method.
I think your solution can be done much simpler than looping through each character
var old_val = 'XBGa_AHjhdjsDjk_sad/safasdf_Sdfsdfasfdsa';
var new_val = old_val.substring(old_val.indexOf('/')+1); //this will find the "/" and take the string after it

javascript spilt to get part of the word

I tried use javascript spilt to get part of the word : new from What#a_new%20day
I tried code like this:
<script>
var word="What#a_new%20day";
var newword = word.split("%20", 1).split("_", 2);
alert(newword);
</script>
But caused:
Uncaught TypeError: Object What#a_new has no method 'split'
Maybe there have more wiser way to get the word which I need. So can anyone help me? Thanks.
split returns an array, so the second split is trying to operate on the array returned by the first, rather than a string, which causes a TypeError. You'll also want to add the correct index after the second call to split, or newword will also be an array, not the String you're expecting. Change it to:
var newword = word.split("%20", 1)[0].split("_", 2)[1];
This splits word, then splits the string at index 0 of the resulting array, and assigns the value of the string at index 1 of the new array to newword.
Regex to the rescue
var word="What#a_new%20day";
var newword = word.match(/_(.+)%/)[1];
alert(newword);
this returns the first ([1]) captured group ((...)) in the regex (_(.+)%) which is _ followed by any character (.) one or more times (+) followed by %.
the result of a split is an array, not a string. so what you need to do is
<script>
var word="What#a_new%20day";
var newword = word.split("%20", 1)[0].split("_", 2);
alert(newword);
</script>
notice the [0]
split returns an array:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split
word.split("%20", 1);
gives an array so you cannot do :
(result from above).split("_", 2);
If split is what your after, go for it, but performance wise, it would be better to do something like this:
var word="What#a_new%20day";
var newword = word.substr(word.indexOf('new'),3)
alert(newword);
Live example: http://jsfiddle.net/qJ8wM/
Split searches for all instances of %20 in the text, whereas indexOf finds the first instance, and substr is fairly cheap performance wise as well.
JsPerf stats on split vs substring (a general case): http://jsperf.com/split-vs-substring

Categories

Resources