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.
Related
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)
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.
How do I increment a string "A" to get "B" in Javascript?
function incrementChar(c)
{
}
You could try
var yourChar = 'A'
var newChar = String.fromCharCode(yourChar.charCodeAt(0) + 1) // 'B'
So, in a function:
function incrementChar(c) {
return String.fromCharCode(c.charCodeAt(0) + 1)
}
Note that this goes in ASCII order, for example 'Z' -> '['. If you want Z to go back to A, try something slightly more complicated:
var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
function incrementChar(c) {
var index = alphabet.indexOf(c)
if (index == -1) return -1 // or whatever error value you want
return alphabet[index + 1 % alphabet.length]
}
var incrementString = function(string, count){
var newString = [];
for(var i = 0; i < string.length; i++){
newString[i] = String.fromCharCode(string[i].charCodeAt() + count);
}
newString = newString.join('');
console.log(newString);
return newString;
}
this function also can help you if you have a loop to go through
Any ideas on the following? I want to input a number into a function and insert dashes "-" between the odd digits. So 4567897 would become "456789-7". What I have so far is to convert the number into a string and then an array, then look for two odd numbers in a row and use the .splice() method to add the dashes where appropriate. It does not work and I figure I may not be on the right track anyway, and that there has to be a simpler solution.
function DashInsert(num) {
var numArr = num.toString().split('');
for (var i = 0; i < numArr.length; i++){
if (numArr[i]%2 != 0){
if (numArr[i+1]%2 != 0) {
numArr.splice(i, 0, "-");
}
}
}
return numArr;
}
The problem is you're changing the thing you're iterating over. If instead you maintain a separate output and input...
function insertDashes(num) {
var inStr = String(num);
var outStr = inStr[0], ii;
for (ii = 1; ii < inStr.length; ii++) {
if (inStr[ii-1] % 2 !== 0 && inStr[ii] % 2 !== 0) {
outStr += '-';
}
outStr += inStr[ii];
}
return outStr;
}
You can try using regular expressions
'4567897'.replace(/([13579])(?=[13579])/g, '$1-')
Regex Explained
So, we find an odd number (([13579]) is a capturing group meaning we can use it as a reference in the replacement $1) ensure that it is followed by another odd number in the non-capturing positive lookahead ((?=[13579])) and replace the matched odd number adding the - prefix
Here is the function to do it:
function dashes(number){
var numString = '';
var numArr = number.toString().split('');
console.log(numArr);
for(i = 0; i < numArr.length; i++){
if(numArr[i] % 2 === 1 && numArr[i+1] % 2 === 1){
numString += numArr[i] + '-';
}else{
numString += numArr[i];
}
}
console.log(numString);
}
dashes(456379);
Tested and everything.
Edit: OrangeDog's answer was posted earlier (by nearly a full half hour), I just wanted to make an answer which uses your code since you're almost there.
Using another array instead of splicing into one you were looping through (this happens to return a string using join):
var num = 4567897;
function DashInsert(num) {
var numArr = num.toString().split('');
var len = numArr.length;
var final = [];
for (var i = 0; i < len; i++){
final.push(numArr[i]);
if (numArr[i]%2 != 0){
if (i+1 < len && numArr[i+1]%2 != 0) {
final.push("-")
}
}
}
return final.join("");
}
alert(DashInsert(num));
function dashInsert(str) {
var arrayNumbers = str.split("");
var newString = "";
for (var i = 0; i < arrayNumbers.length; i++){
if(arrayNumbers[i] % 2 === 1 && arrayNumbers[i + 1] % 2 === 1){
newString = newString + arrayNumbers[i] + "-";
} else {
newString = newString + arrayNumbers[i];
}
}
return newString;
}
var result = dashInsert("3453246");
console.log(result);
I would like to have a function which takes 3 arguments:
sentence (string),
maxCharLen=20 (number),
separator (string)
and transform the sentence based on the parameters.
Example
var sentence = "JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions."
var newSentence = breakSentence(sentence, maxCharLen=20, separator="<br>");
newSentence // JavaScript is a prototype-based <br> scripting language that is dynamic, <br> weakly typed and has first-class functions.
P.S:
This is what I have tried:
var breakSentence = function (sentence, maxCharLen, separator)
{
sentence = sentence || "javascript is a language" ;
maxCharLen = 10 || maxCharLen; // max numb of chars for line
separator = "<br>" || separator;
var offset;
var nbBreak = sentence.length // maxCharLen;
var newSentence = "";
for (var c = 0; c < nbBreak; c += 1)
{
offset = c * maxCharLen;
newSentence += sentence.substring(offset, offset + maxCharLen) + separator;
}
return newSentence;
}
It works in this way:
breakSentence() // "javascript<br> is a lang<br>uage<br>"
it should be:
breakSentence() // "javascript<br>is a <br>language"
Here's a solution: http://snippets.dzone.com/posts/show/869
//+ Jonas Raoni Soares Silva
//# http://jsfromhell.com/string/wordwrap [v1.0]
String.prototype.wordWrap = function(m, b, c){
var i, j, l, s, r;
if(m < 1)
return this;
for(i = -1, l = (r = this.split("\n")).length; ++i < l; r[i] += s)
for(s = r[i], r[i] = ""; s.length > m; r[i] += s.slice(0, j) + ((s = s.slice(j)).length ? b : ""))
j = c == 2 || (j = s.slice(0, m + 1).match(/\S*(\s)?$/))[1] ? m : j.input.length - j[0].length
|| c == 1 && m || j.input.length + (j = s.slice(m).match(/^\S*/)).input.length;
return r.join("\n");
};
usage:
var sentence = "JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions."
sentence.wordWrap(20, "<br>",true)
// Output "JavaScript is a <br>prototype-based <br>scripting language <br>that is dynamic, <br>weakly typed and has<br> first-class <br>functions."
I would try it like that (not tested):
var breakSentence = function (sentence, maxCharLen, separator)
{
var result = "";
var index = 0;
while (sentence.length - index > maxCharLen)
{
var spaceIndex = sentence.substring(index, index + maxCharLen).lastIndexOf(' ');
if (spaceIndex < 0) //no spaces
{
alert('Don\'t know what do do with substring with one long word');
spaceIndex = maxCharLen; //assume you want to break anyway to avoid infinite loop
}
result += sentence.substring(index, index + spaceIndex + 1) + separator;
index += spaceIndex + 1;
}
return result;
}
Should break after spaces only now...
Here is my attempt to get it. It has two things you should notice:
it first removes all the separator instances (so the reordering is completely new)
it doesn't break words longer then maxCharLen characters.
It worked in node 0.6.10
var breakSentence = function (sentence, maxCharLen, separator) {
var words = [] // array of words
, i // iterator
, len // loop
, current = '' // current line
, lines = [] // lines split
;
sentence = sentence || "javascript is a language";
maxCharLen = 10 || maxCharLen;
separator = separator || "<br>";
sentence = sentence.replace(separator, '');
if (sentence.length < maxCharLen) return [sentence]; // no need to work if we're already within limits
words = sentence.split(' ');
for (i = 0, len = words.length; i < len; i += 1) {
// lets see how we add the next word. if the current line is blank, just add it and move on.
if (current == '') {
current += words[i];
// if it's not like that, we need to see if the next word fits the current line
} else if (current.length + words[i].length <= maxCharLen) { // if the equal part takes the space into consideration
current += ' ' + words[i];
// if the next word doesn't fit, start on the next line.
} else {
lines.push(current);
current = words[i];
// have to check if this is the last word
if (i === len -1) {
lines.push(current);
}
}
}
// now assemble the result and return it.
sentence = '';
for (i = 0, len = lines.length; i < len; i += 1) {
sentence += lines[i];
// add separator if not the last line
if (i < len -1) {
sentence += separator;
}
}
return sentence;
}