Double Spaces in Javascript - javascript

This code should show an alert box if there are no double spaces but it's not doing that.
var str = prompt("Enter Some Text");
var numChars = str.length;
for (var i = 0; i < numChars; i++) {
if (str.slice(i, i + 2) === " ") {
alert("No double spaces!");
break;
}
}
alert will pop out if no double spaces

You could make this a little simpler with an indexOf check:
var str = prompt("Enter Some Text");
if (str.indexOf(" ") === -1) {
alert("No double spaces!");
}

a simple regular expression can do it :
const str = prompt("Enter Some Text");
!/\s\s/.test(str) && alert('No double spaces found !');

If you want to keep that with the for approach, you should invert the logic and check whether the double whitespace occurs:
var str = prompt("Enter Some Text");
var numChars = str.length;
var doubleWhitespace = false;
for (var i = 0; i < numChars; i++) {
// get the current and next character.
var [curr, next] = [str[i], str[i + 1]];
// if both exists and current is the same as next and both the characters are spaces
if (curr && next && curr === next && curr === ' ') {
// double white space.
doubleWhitespace = true;
break;
}
}
if (doubleWhitespace) alert('There is a double space!');
else alert('NO double space');
However, there is a slightly easier solution by just using indexOf:
var str = prompt("Enter Some Text");
if (str.indexOf(' ') > -1) alert("There are double spaces!");
else alert("There are no double spaces!");

you need change this line
if (str.slice(i, i + 2) === " ") {
with
if (str.slice(i, i + 2) === " ") {

Related

Is there a way to match every letter in a string and insert a specific letter in their place?

For example if I had the string "GCG", I'd like to insert a
"C" at every "G" match, and a "G" at every "C" match, making it GCCGGC.
So far I have the following, but it prints GCGCGC.
function pairElement(str) {
for(i = 0; i < str.length; i++) {
if(str[i] == "G") {
return str.replace(/([GC+/])/g, "GC");
} else if (str[i] == "C") {
return str.replace(/([?=CG+/])/g, "CG");
}
}
}
pairElement("GCG");
Edit: I think only the first if statement is executing and not running the else if. Are there any other methods I can use to search for different letters, not only one, and insert another letter depending on what the search for letter is?
You can convert the string into array using splitand then iterate through the array and replace each character.
Then you can use join to convert the array into string.
var string = 'GCG';
var str = string.split('').map(c => {
if(c === 'G') c = 'GC';
else if (c === 'C') c = 'CG';
return c;
}).join('');
console.log('String ' + string);
console.log('New String ' + str);
you can do
function pairElement(str) {
return str.replace(/G|C/g, e => e=='G'?'GC':'CG')
}
console.log(pairElement("GCG"));
You are not using recursion. Once it hits the return statement, the control exits. A better way would be to use regex as one of the answers suggested but if you want to just make tiny modifications in your own code, maybe try something like this.
function pairElement(str) {
var newStr= ""; // using new string to make it more readible
for(i = 0; i < str.length; i++) {
if(str[i] == "G") {
newStr = newStr + str[i] + "C";
} else if (str[i] == "C") {
newStr = newStr + str[i] + "G";
} else {
newStr = newStr + str[i]; //you didn't specify what do you want to do in this case
}
}
return newStr;
}
pairElement("GCG");

Without using a data structure, display whether each character in a string is unique

Without using a data structure, I need to display whether each character in a string is unique or not.
I wrote the code and it works for paa but it doesn't work for pak.
var String = "paa"
//var String = "pak"
var splittedString = String.split();
for(i = 0; i < splittedString.length; i++) {
if(splittedString[i] === splittedString[i+ 1] ||
splittedString[i+1] === splittedString[i + 2]) {
console.log("not unique string");
} else {
console.log("its an unique string")
}
}
It is clearly stated in the problem don't need to use the data structure. I saw above answers using an array. I try to solve this issue in C#. Let me know if you have any feedback.
public bool IsUnique(string text)
{
if (text.Length > 256) return false;
for (var indx = 0; indx < text.Length; indx++)
{
for (var jndx = indx + 1; jndx < text.Length; jndx++)
{
// compare character
if (text.Substring(indx, 1) == text.Substring(jndx, 1) )
{
return false;
}
}
}
return true;
}
Just to show the needed change in your code, plus nice output as per Emile's request:
var str = "palace";
//var str = "pak";
var splittedString = str.split('');
for (i=0; i<splittedString.length; i++) {
var c = splittedString[i];
var unique = true;
for (j=0; j <splittedString.length; j++) {
if (i==j) continue;
if (c === splittedString[j]) {
unique = false;
break;
}
}
console.log("'" + c + "' is" + (unique ? '': ' not') + " unique character");
}
First you sort the characters in the string and then compare each one to the next.
The program with regex may look like below
var str = "alphabet";
var sstr = str.split('').sort().join('');
var result = /(.)\1/.test(sstr);
console.log(sstr + " has dups: " + result)

Manually remove whitespace in String - JavaScript

I have attempted to make an algorithm that will do the same thing as this function: var string= string.split(' ').join('');
So if I have the following String: Hello how are you it becomes Hellohowareyou
I don't want to use .replace or regex or .split
However, the algorithm doesn't seem to make any changes to the String:
var x = prompt("Enter String");
for (var i=0; i<=x.length;i++) {
if (x[i] == " ") {
x[i] = "";
}
}
alert(x);
Iterate over the string copying characters, skipping spaces. Your code doesn't work because strings are immutable, so you cannot change characters within the string by doing x[i] = 'c'.
See Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
var string = 'Hello How are you';
var noSpaces = '';
for (var i = 0; i < string.length; i++) {
if (string.charAt(i) != ' ' ) {
noSpaces += string.charAt(i);
}
}
alert(noSpaces);
Your code is not working because, probably for strings, similar to a getter, there is no setter for indexed approach(x[0] = "w"). You cannot consider a string as an array. Its a special form of object (immutable object) that can be accessed with index, but strictly there is no setter in this approach.
You can fix your code by changing like below,
var x = prompt("Enter sum or 'e' to Exit");
var modified = "";
for (var i=0; i<x.length;i++) {
if (x[i] != " ") {
modified += x[i];
}
}
alert(modified);
And you can do this in other better ways like below by using regex,
var x = prompt("Enter sum or 'e' to Exit");
x = x.replace(/\s/g,"");
In your code you just compare the value and try to replace with same variable but it's not possible to replace same with variable, just stored your value with new variable some thing like below
var x = prompt("Enter sum or 'e' to Exit");
var v='';
for (var i=0; i<x.length;i++) {
if (x[i] != " ") {
v +=x[i];
}
}
alert(v);
Here is the link https://jsfiddle.net/rqL3cvog/
Another approach, which updates the variable x and does not use another variable is to use a reverse for loop and use slice to take the string before and after i:-
var x = prompt("Enter String");
for (var i = x.length; i--;) {
if (x[i] == " ") {
x = x.slice(0, i) + x.slice(i + 1, x.length);
}
}
alert(x);
Or, a reverse for loop with substr :-
var x = prompt("Enter String");
for (var i = x.length; i--;) {
if (x[i] == " ") {
x = x.substr(0, i) + x.substr(i + 1);
}
}
alert(x);
Hie ,
Please check below code. Its lengthy. But others can help to make it short. Check output
var x = prompt("Hello how are you");
y = ''
flag = false
for (var i=0; i<x.length;i++) {
if (x[i] == " ") {
flag= true
}
else {
if (flag == true) {
y += ' '
y += x[i]
flag = false
}
else {
y += x[i]
}
}
}
alert(y)
Output is : "Hello how are you"
Code just sets a flag when you get a space in x[i] & when you get next character its just add single space instead of whitespace & adds next character to output string & again sets flag to false.

Debugging JavaScript for Palindrome Function

function palindrome(str) {
str = str.replace(' ', '');
str = str.replace(',', '');
str = str.replace('.', '');
str = str.toLowerCase();
if (str.length % 2 === 0) {
var x = 0;
while (x < (str.length - x)) {
if (str.charAt(x) === str.charAt((str.length - x) - 1)) {
x++;
} else {
return false;
}
}
return true;
} else {
var y = 0;
while (y < (str.length - y - 1)) {
if (str.charAt(y) === str.charAt((str.length - y) - 1)) {
y++;
} else {
return false;
}
}
return true;
}
}
palindrome("eye");
This may not be the most effecient way of solving this, but I begin by remove extraneous characters, then I used an if/else to split out even and odd string lengths. Within each, I only check equality of characters up through the middle of the word - since past that would be repetitious.
However, after multiple changes and looking into other solutions for the problem, I still cannot get mine to pass for a particular case: palindrome("never odd or even")
If it helps, it passes for "race car" and "almostomla" and "eye".
Thanks in advance!
The problem is that the native replace Javascript function is only replacing a single occurrence in the string. Use Regex to account for all of the matches within the string.
However, keep in mind that the "." character is used in Regex as a wildcard so you need to escape it with a backslash to tell Regex you're specifically looking for the "." character. See this JSFiddle as an example: https://jsfiddle.net/on333yf9/3/
function palindrome(str) {
str = str.replace(/ /g, '');
str = str.replace(/,/g, '');
str = str.replace(/\./g, '');
str = str.toLowerCase();
if (str.length % 2 === 0) {
var x = 0;
while (x < (str.length - x)) {
if (str.charAt(x) === str.charAt((str.length - x) - 1)) {
x++;
} else {
return false;
}
}
return true;
} else {
var y = 0;
while (y < (str.length - y - 1)) {
if (str.charAt(y) === str.charAt((str.length - y) - 1)) {
y++;
} else {
return false;
}
}
return true;
}
}
The problem is because of the following lines:
str = str.replace(' ', '');
str = str.replace(',', '');
str = str.replace('.', '');
It does replace all white spaces, commas or dots globally, it just replaces one space, comma and dot, if it's there. You have to find all spaces, commas and dots and remove them. This is what you can do,
str = str.replace(/ /g, '');
str = str.replace(/,/g, '');
str = str.replace(/./g, '');
The g character means to repeat the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.
Edited:
You can do something like this:
if(str.replace(/ /g, '').length != 0){
str = str.replace(/ /g, '');
}
if(str.replace(/,/g, '').length != 0){
str = str.replace(/,/g, '');
}
if(str.replace(/\./g, '').length != 0){
str = str.replace(/\./g, '');
}
Unless you want to write your own code why not user reverse/join?
function palindrome(str)
{
str = str.split(' ').join('');
str = str.split(',').join('');
str = str.split('.').join('');
str = str.toLowerCase();
if (str.split('').reverse().join('') == str)
{
return true;
}
else
{
return false;
}
}
palindrome("never odd or even");

Is there a way I can change the contents of a variable in Camel Case to space separated words?

I have a variable which contains this:
var a = "hotelRoomNumber";
Is there a way I can create a new variable from this that contains: "Hotel Room Number" ? I need to do a split on the uppercase character but I've not seen this done anywhere before.
Well, you could use a regex, but it's simpler just to build a new string:
var a = "hotelRoomNumber";
var b = '';
if (a.length > 0) {
b += a[0].toUpperCase();
for (var i = 1; i != a.length; ++i) {
b += a[i] === a[i].toUpperCase() ? ' ' + a[i] : a[i];
}
}
// Now b === "Hotel Room Number"
var str = "mySampleString";
str = str.replace(/([A-Z])/g, ' $1').replace(/^./, function(str){ return str.toUpperCase(); });
http://jsfiddle.net/PrashantJ/zX8RL/1/
I have made a function here:
http://jsfiddle.net/wZf6Z/2/
function camelToSpaceSeperated(string)
{
var char, i, spaceSeperated = '';
// iterate through each char
for (i = 0; i < string.length; i++) {
char = string.charAt(i); // current char
if (i > 0 && char === char.toUpperCase()) { // if is uppercase
spaceSeperated += ' ' + char;
} else {
spaceSeperated += char;
}
}
// Make the first char uppercase
spaceSeperated = spaceSeperated.charAt(0).toUpperCase() + spaceSeperated.substr(1);
return spaceSeperated;
}
The general idea is to iterate through each char in the string, check if the current char is already uppercased, if so then prepend a space to it.

Categories

Resources