why don't replace all letter from second array last13? - javascript

My problem is that replace only first character from last13 array.
I want replace all character from var last13 to first13
var first13 = first13Letter.map(x=>x).join(',');
var last13 = last13Letter.map(y=>y).join(',');
my code
function rot13(str) {
var first13Letter = ["A","B","C","D","E","F","G","H","I","J","K","L","M"];
var last13Letter = ["N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var first13 = first13Letter.map(x=>x).join(',');
var last13 = last13Letter.map(y=>y).join(',');
for(let i=0; i<first13.length; i++){
if(str.indexOf(first13[i]) !== -1){
str = str.replace(first13[i],last13[i])
}else{
str = str.replace(last13[i],first13[i]) // i want to replace all letter from last13 to first13 letter but this replace only first letter.
}
}
return str;
}
console.log(rot13("SERR YBIR?"))
//output:"FRRR LOVR?"
//expect output: "FREE LOVE?"
What is the error in code above?

function rot13(str) {
const first13Letter = ["A","B","C","D","E","F","G","H","I","J","K","L","M"];
const last13Letter = ["N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
return str.split('')
.map(s => last13Letter.indexOf(s) >= 0 ? first13Letter[last13Letter.indexOf(s)] :
first13Letter.indexOf(s) >= 0 ? last13Letter[first13Letter.indexOf(s)] : s)
.join('')
}
console.log(rot13("SERR YBIR?"))

Related

Specific Array element replace

I'm solving a simple problem where I need to capitalize the first alphabet of all words. I was able to do that but I have another string vn52tqsd0e4a if any of my output is matched with this string I have to replace it with --[matched string]-- .
so the expected output should be H--e--llo Worl--d--
but when I'm trying to replace the element with -- it's not doing anything. I tried replace() method as well but it didn't work. I don't know what I'm doing wrong here.
function LetterCapitalize(str) {
// code goes here
let array = str.split(" ")
for (let i=0; i<array.length; i++){
array[i] = array[i].charAt(0).toUpperCase() + array[i].slice(1)
}
let output = array.join(" ") ;
let comp = "vn52tqsd0e4a".split("");
for (let i=0; i<output.length; i++){
comp.map(el=> {
if(output[i] === el){
console.log( `matched ${output[i]}` )
output[i] = `--${output[i]}--`;
console.log(output[i]);
}
})
//
}
console.log(output);
}
LetterCapitalize("hello world");
You can achieve this using split, map, join as:
function LetterCapitalize(str) {
// code goes here
let array = str.split(' ');
for (let i = 0; i < array.length; i++) {
array[i] = array[i].charAt(0).toUpperCase() + array[i].slice(1);
}
let output = array.join(' ');
let comp = 'vn52tqsd0e4a'.split('');
const result = output
.split('')
.map((c) => (comp.includes(c) ? `--${c}--` : c))
.join('');
console.log(result);
}
LetterCapitalize('hello world');
You coulduse Array.reduce() to iterate over the str argument and either capitalize or replace depending on the character.
If the preceeding value is a space we'll capitalize, otherwise if the character is in the comp value, we'll replace with --${char}--.
function LetterCapitalize(str) {
const comp = "vn52tqsd0e4a";
return [...str].reduce((acc, char, idx, a) => {
if (idx === 0 || a[idx - 1] === ' ') {
char = char.toUpperCase();
} else if (comp.includes(char)) {
char = `--${char}--`;
}
return acc + char;
}, '')
}
console.log(LetterCapitalize("hello world"));
console.log(LetterCapitalize("hey man"));
What you say to JavaScript in the piece of code is that it should fit 5 characters in a place that can only hold one character.
output[i] = `--${output[i]}--`;
You need to change it to something like this (code below may not work):
output = output.substring(0,i-1) + el + output.substring(i+1,output.length - i-1);
I recommend using the string.replaceAll function instead. If you create a loop yourself you'll get problems when adding more characters on a place where original one character was present.
function LetterCapitalize(str) {
// code goes here
let array = str.split(" ")
for (let i=0; i<array.length; i++){
array[i] = array[i].charAt(0).toUpperCase() + array[i].slice(1)
}
let output = array.join(" ") ;
let comp = "vn52tqsd0e4a".split("");
comp.map(el=> {
output = output.replaceAll(el, '--' + el + '--');
});
console.log(output);
}
LetterCapitalize("hello world");

How to change (manipulate) char string depend on giving value

i want to ask how to manipulate char in string depends on giving value
my string
"---x---x---x------x"
when im input a value = 2
char "x" was changed to "o" in 2 times
my expected value is
"---o---o---x------x"
thank you in advance
based on solution here:
var str = "---x---x---x------x"
var n = 0
var N = 2
var newStr = str.replace(/x/g,s => n++<N ? 'o' : s)
const x = "---x---x---x------x";
let input = 2;
let output = [];
for (const dashes of x.split("x")) {
output.push(dashes);
if (input > 0) {
input--;
output.push("o");
} else {
output.push("x");
}
}
output.pop();
output = output.join("");
console.log({ output });
You can just loop over the and replace x with o until value becomes 0(which is falsy value)
let str = "---x---x---x------x";
let value = 2;
while (value--) {
str = str.replace("x", "o");
}
console.log(str);

Find second occurrence of a character in a string

I have heard that JavaScript has a function called search() that can search for a string ( lets call it A ) in another string ( B ) and it will return the first position at which A was found in B.
var str = "Ana has apples!";
var n = str.search(" ");
The code should return 3 as its the first position in which the space was found in str.
And I was wondering if there is a function that can find the next spaces in my string.
For example I want to find the length of the first word in my string and I could easily do this If I knew the its starting position and its ending one.
If there is such a function, are there any better than it for such things?
You need to use String.indexOf method. It accepts the following arguments:
str.indexOf(searchValue[, fromIndex])
So you can do this:
var str = "Ana has apples!";
var pos1 = str.indexOf(" "); // 3
var pos2 = str.indexOf(" ", pos1 + 1); // 7
console.log(pos2 - pos1 - 1); // 3... length of the second word
.indexOf(…) will give you the first occurence of the " " (starting at 0):
var str = "Ana has apples!";
var n = str.indexOf(" ");
console.log(n);
If you want all occurences, this can be achieved easily using a RegExp with a while:
var str = "Ana has apples! A lot.";
var re = new RegExp(" ","ig");
var spaces = [];
while ((match = re.exec(str))) {
spaces.push(match.index);
}
// Output the whole array of results
console.log(spaces);
// You can also access the spaces position separately:
console.log('1st space:', spaces[0]);
console.log('2nd space:', spaces[1]);
⋅
⋅
⋅
Or… you can use a do {} while () loop:
var str = "Ana has apples! A lot.";
var i = 0,
n = 0;
do {
n = str.indexOf(" ");
if (n > -1) {
i += n;
console.log(i);
str = str.slice(n + 1);
i++;
}
}
while (n > -1);
Then, you can make a function of it:
var str = "Ana has apples! A lot.";
// Function
function indexsOf(str, sub) {
var arr = [],
i = 0,
n = 0;
do {
n = str.indexOf(" ");
if (n > -1) {
i += n;
arr.push(i);
str = str.slice(n + 1);
i++;
}
}
while (n > -1);
return arr;
}
var spaces = indexsOf(str, ' ')
// Output the whole array of results
console.log(spaces);
// You can also access the spaces position separately:
console.log('1st space:', spaces[0]);
console.log('2nd space:', spaces[1]);
⋅
⋅
⋅
Hope it helps.
Better for matching is to use regex. There is option like match group using group 'g' flag
var str = "Ana has apples !";
var regBuilder = new RegExp(" ","ig");
var matched = "";
while((matched = regBuilder.exec(str))){
console.log(matched + ", position : " +matched.index);
}
str = "Ana is Ana no one is better than Ana";
regBuilder = new RegExp("Ana","ig");
while((matched = regBuilder.exec(str))){
console.log(matched + ", position : " +matched.index);
}
'i' flag used to ignore case sensitive
You can check for other flags too here
Try this:
const str = "Ana has apples!";
const spaces = str.split('')
.map((c, i) => (c === ' ') ? i : -1)
.filter((c) => c !== -1);
console.log(spaces);
Then you will all the spaces positions.

Replace letters in string with the next letter, and capitalize vowels in the changed string

function LetterChanges(str) {
var alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (var i = 0; i < str.length; i++) {
var index = alphabet.indexOf(str[i])
if (/[a-zA-Z]/.test(str[i])) {
str = str.replace(str[i], alphabet.charAt(index + 1));
}
if (/[aeiou]/.test(str[i])) {
str = str.replace(str[i], alphabet.charAt(index + 26));
}
}
return str;
}
When I call LetterChanges("hello"), it returns 'Ifmmp' which is correct, but when "sent" is passed it returns 'ufOt' instead of 'tfOu'. Why is that?
str.replace() replaces the first occurrence of the match in the string with the replacement. LetterChanges("sent") does the following:
i = 0 : str.replace("s", "t"), now str = "tent"
i = 1 : str.replace("e", "f"), now str = "tfnt"
i = 2 : str.replace("n", "o"), now str = "tfot", then
str.replace("o", "O"), now str = "tfOt"
i = 3 : str.replace("t", "u"), now str = "ufOt"
return str
There are several issues. The main one is that you could inadvertently change the same letter several times.
Let's see what happens to the s in sent. You first change it to t. However, when it comes to changing the final letter, which is also t, you change the first letter again, this time from t to u.
Another, smaller, issue is the handling of the letter z.
Finally, your indexing in the second if is off by one: d becomes D and not E.
You can use String.replace to avoid that:
function LetterChanges(str) {
return str.replace(/[a-zA-Z]/g, function(c){
return String.fromCharCode(c.charCodeAt(0)+1);
}).replace(/[aeiou]/g, function(c){
return c.toUpperCase();
});
}
But there is still a bug: LetterChanges('Zebra') will return '[fcsb'. I assume that is not your intention. You will have to handle the shift.
Try this one:
function LetterChanges(str) {
var alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var result = '';
var temp;
for (var i = 0; i < str.length; i++) {
var index = alphabet.indexOf(str[i])
if (/[a-zA-Z]/.test(str[i])) {
//str = str.replace(str[i], alphabet.charAt(index + 1));
temp= alphabet.charAt(index + 1);
index = index+1;
}
else if(str[i] == ' '){
temp = ' ';
}
if (/[aeiou]/.test(temp)) {
temp = alphabet.charAt(index + 26);
}
result += temp;
}
return result;
}
var str = 'bcd12';
str = str.replace(/[a-z]/gi, function(char) { //call replace method
char = String.fromCharCode(char.charCodeAt(0)+1);//increment ascii code of char variable by 1 .FromCharCode() method will convert Unicode values into character
if (char=='{' || char=='[') char = 'a'; //if char values goes to "[" or"{" on incrementing by one as "[ ascii value is 91 just after Z" and "{ ascii value is 123 just after "z" so assign "a" to char variable..
if (/[aeiuo]/.test(char)) char = char.toUpperCase();//convert vowels to uppercase
return char;
});
console.log(str);
Check this code sample. There is no bug in it. Not pretty straight forward but Works like a charm. Cheers!
function LetterChanges(str) {
var temp = str;
var tempArr = temp.split("");//Split the input to convert it to an Array
tempArr.forEach(changeLetter);/*Not many use this but this is the referred way of using loops in javascript*/
str = tempArr.join("");
// code goes here
return str;
}
function changeLetter(ele,index,arr) {
var lowerLetters ="abcdefghijklmnopqrstuvwxyza";
var upperLetters ="ABCDEFGHIJKLMNOPQRSTUVWXYZA";
var lowLetterArr = lowerLetters.split("");
var upLetterArr = upperLetters.split("");
var i =0;
for(i;i<lowLetterArr.length;i++){
if(arr[index] === lowLetterArr[i]){
arr[index] = lowLetterArr[i+1];
arr[index]=arr[index].replace(/[aeiou]/g,arr[index].toUpperCase());
return false;
}
if(arr[index] === upLetterArr[i]){
arr[index] = upLetterArr[i+1];
arr[index]=arr[index].replace(/[aeiou]/g,arr[index].toUpperCase());
return false;
}
}
}
// keep this function call here
// to see how to enter arguments in JavaScript scroll down
LetterChanges(readline());

Want to get specific value from string

I have a JavaScript string sentrptg2c#appqueue#sentrptg2c#vwemployees#.
I want to get last string vwemployees through RegExp or from any JavaScript function.
Please suggest a way to do this in JavaScript.
You can use the split function:
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
str = str.split("#");
str = str[str.length-2];
alert(str);
// Output: vwemployees
The reason for -2 is because of the trailing #. If there was no trailing #, it would be -1.
Here's a JSFiddle.
var s = "...#value#";
var re = /#([^#]+)#^/;
var answer = re.match(s)[1] || null;
if you're sure the string will be separated by "#" then you can split on # and take the last entry... I'm stripping off the last #, if it's there, before splitting the string.
var initialString = "sentrptg2c#appqueue#sentrptg2c#vwemployees#"
var parts = initialString.replace(/\#$/,"").split("#"); //this produces an array
if(parts.length > 0){
var result = parts[parts.length-1];
}
Try something like this:
String.prototype.between = function(prefix, suffix) {
s = this;
var i = s.indexOf(prefix);
if (i >= 0) {
s = s.substring(i + prefix.length);
}
else {
return '';
}
if (suffix) {
i = s.indexOf(suffix);
if (i >= 0) {
s = s.substring(0, i);
}
else {
return '';
}
}
return s;
}
No magic numbers:
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
var ar = [];
ar = str.split('#');
ar.pop();
var o = ar.pop();
alert(o);
jsfiddle example

Categories