Reversing a string with terminating punctuation results in errors - javascript

I am tyring to reverse a string in javascript with the following code.
const reverseString = str => [...str].sort(() => 1).join('');
All my test are passing, except the one in which the string contains punctuations at the end. e.g hungry!, sharpshooter^. What is causing the error?
Test results
Input: "I am hungry!"
Expected: "!yrgnuh ma I"
Received: "u!Iyrgn h ma"
Input: "sharpshooter^"
Expected: "^retoohsprahs"
Received: "h^osaretorhsp"

I guess its because position in ASCII table, why wouldn't you use reverse() ?
const reverseString = str => [...str].reverse().join('')

You can use reverse() to reverse the array before joining the array elements.
function reverseString(str){
return [...str].reverse().join('');
}
console.log(reverseString("I am hungry!"));
console.log(reverseString("sharpshooter^"));

Try this:
const reverseString = str => [...str].sort(() => -1).join('');
or even better...
const reverseString = str => [...str].reverse().join('');

If you don't want to use split reverse and join, use a simple loop
function reverseString(str){
let length = str.length
let final = ''
while(length-- > 0){
final+= str[length]
}
return final
}
console.log(reverseString("I am hungry!"));
console.log(reverseString("sharpshooter^"));

Related

how to print all values from an array containing a given string value (JavaScript)

Given an array like the below code :
let words = ['bring','constant','bath','spring','splashing']
How do I print all string characters with ing characters from the words array ?
You need to use endsWith method to check if the word ends with a specific value.
let words = ['bring','constant','bath','spring','splashing']
const result = words.filter(w => w.endsWith('ing'))
result.forEach(w => console.log(w))
You also can use regular expressions with dollar sign $ means end with.
let words = ['bring','constant','bath','spring','splashing']
const result = words.filter(w => /(ing)$/.test(w))
result.forEach(w => console.log(w))
As author want to check if ing exist in the middle of the word or not. In that case you can just use normal regex with String.match() method without $ sign at end.
Live Demo :
let words = ['bring','constant','bath','spring','splashing', 'tingtong'];
const res = words.filter(word => word.match(/ing/ig));
console.log(res);
Or you can also achieve that by using .includes() method.
Live Demo :
let words = ['bring','constant','bath','spring','splashing', 'tingtong'];
const res = words.filter(word => word.includes('ing'));
console.log(res);

javascript split string like object/array to nodes

I have a string like object/array nodes. need to convert string to nodes, using regular expression
const variableName = "parent1[0].child[2].grandChild['name'].deep_child"; // should be n number of child`
// expected result:
const array = ['parent1',0,'child',2,'grandChild','name','deepChild'];
// Note: array's strings property should be any valid variable name like 'parenet' or 'parent1' or 'PARENT' or '_parent_' or 'deep_child'
Note
You can get the desired result by using split
[^\w]
after splitting you may get empty strings so you can use a filter to filter out them. At last convert the required number that are in string to type number
const variableName = "parent1[0].child[2].grandChild['name'].deep_child";
const result = variableName
.split(/[^\w]/)
.filter(_ => _)
.map(a => (isNaN(parseInt(a)) ? a : parseInt(a)));
console.log(result);
Try with regex /[\[\].']+/g.
Regex Evaluator.
This regex catches the group between [ and ]. and splits the string there. Also if ant node of the generated array is a number, convert that to a number using a map function.
const variableName = "parent1[0].child[2].grandChild['name'].deep_child";
const output = variableName
.split(/[\[\].']+/g)
.map((node) => isNaN(node) ? node : Number(node));
console.log(output);
What you are looking for is a split of multiple conditions. A simple and good aproach is to replace all of them except one and finally make the split:
// should be n number of child`
const variableName = "parent1[0].child[2].grandChild['name'].deep_child";
const array = variableName
.replaceAll("'", "")
.replaceAll("].", "[")
.split("[")
.map((x) => (isNaN(x) ? x : +x));
console.log(array);

How do you remove the first number followed by comma in regex?

If I have strings ["32145","yes","no","0"] how would like: ,"yes","no","0"? Right now I have the regex below, but that gives me ,yes,no,
.replace(/["'\\[\\]\d]/g,"")
How do I just remove the first number and first comma following that number?
Maybe,
\["\d+",|[\]"]
being replaced with an empty string would work OK.
const regex = /\["\d+",|[\]"]/g;
const str = `["32145","yes","no","0"] `;
const subst = ``;
const result = str.replace(regex, subst);
console.log(result);
Demo
RegEx Circuit
jex.im visualizes regular expressions:
Here is a solution without regex using JSON.parse().
var str = '["32145","yes","no","0"]';
var result = JSON.parse(str); // Convert string to array.
result.shift(); // Remove first array element.
result = result.toString(); // Convert array to string.
console.log(result);
Simply parse the value and remove the first element which is a number
let firstNumRemover = (str) => {
let removeFurther = true
return JSON.parse(str).filter(v => {
if (!isNaN(v) && removeFurther) {
removeFurther = false
return false
}
return true
}).toString()
}
console.log(firstNumRemover(`["32145","yes","no","0"]`))
console.log(firstNumRemover(`["Some random text", "32145","yes","no","0"]`))

How to get the string just before specific character in JavaScript?

I have couple of strings like this:
Mar18L7
Oct13H0L7
I need to grab the string like:
Mar18
Oct13H0
Could any one please help on this using JavaScript? How can I split the string at the particular character?
Many Thanks in advance.
For var str = 'Mar18L7';
Try any of these:
str.substr(0, str.indexOf('L7'));
str.split('L7')[0]
str.slice(0, str.indexOf('L7'))
str.replace('L7', '')
Based on input that is given it I have created following function which can take n string in array and return the output in the format you have given. Check if this helps and if some use case is missed.
function generateStr(arr, splitStr) {
const processedStr = arr.map(value => value.split(splitStr)[0]);
return processedStr.join(" OR ");
}
console.log(generateStr(["Mar18L7", "Oct13H0L7"], "L7"));
You can use a regex like this
var data = ["Mar18L7", "Oct13H0L7"];
var regex = /^([a-zA-Z0-9]+)\L[a-zA-Z0-9]+$/;
var output = []
data.forEach(function(el){
var matches = el.match(regex);
output.push(matches[1]);
});
output variable will be equal to ['Mar18', 'Oct13H0'] and you can join all value usin the .join method on output array
var chain = output.join(" OR ");
// chain will be equal to "Mar18 OR Oct13H0"

Split a declartion of an array string into an array of strings

What would be the best way to split an a string that a declaration of an array into an array of strings using javascript/jquery. An example of a string I am working with:
franchise[location][1][location_name]
I would like it to be converted into an array like:
['franchise', 'location', '1', 'location_name']
BONUS: If I could also get that numeric value to be an integer and not just a string in one fell swoop, that would be terrific.
You can use String.split with a regex that matches all the none alpha numeric chars.
Something like that:
const str = 'franchise[location][1][location_name]';
const result = str.split(/\W+/).filter(Boolean);
console.log(result);
One option would be to just match word characters:
console.log(
'franchise[location][1][location_name]'.match(/\w+/g)
);
To transform the "1" to a number, you might .map afterwards:
const initArr = 'franchise[location][1][location_name]'.match(/\w+/g);
console.log(initArr.map(item => !isNaN(item) ? Number(item) : item));
You could try
const str = 'franchise[location][1][location_name]';
const res = str.split(/\W+/).map(i => { return Number(i) ? Number(i) : i;})

Categories