Split string into even numbers forming a square [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
My objective is to split string (less than 80 characters) evenly to create a square or rectangle of strings.
var squareStr = function(str) {
}
console.log(squareStr('whatwonderfulday'));
console.log(squareStr('if life was easy god then god would not have given us brain to think'));
should output:
what
wond
erfu
lday
iflifewa
seasythe
ngodwoul
dnothave
givenusb
raintoth
ink
is this possible? I've been told I can use Math.sqrt but I'm not too sure how.
Thanks.

You can use a for loop to slice the string into the pieces and add a new line (\n) at the end of each chunk.
If you want to automatically use the square root of the string length you can do it like this:
function squareCode(string){
let squareString = "";
string = string.replace(/\s/g, '');
const splitNum = Math.floor(Math.sqrt(string.length));
for(i=0; i<= string.length; i+=splitNum){
squareString = `${squareString}${string.slice(i, i+splitNum)}\n`;
}
return squareString;
}
console.log(squareCode('whatwonderfulday'));
console.log(squareCode('if life was easy god then god would not have given us brain to think'));
console.log(squareCode('asdfasdf asdfasdfasd fasdfwe wer df gf dgdfgertqewdfsf fgdgewfwdsgewerfsd fdgdfgqefasdf'));
In the following function you'll pass in the string you want to slice as well as the number you want to slice at:
function squareCode(string, splitNum){
let squareString = "";
string = string.replace(/\s/g, '');
for(i=0; i<= string.length; i+=splitNum){
squareString = `${squareString}${string.slice(i, i+splitNum)}\n`;
}
return squareString;
}
console.log(squareCode('whatwonderfulday', 4));
console.log(squareCode('if life was easy god then god would not have given us brain to think', 8));

You could use this function. It replace all the empty spaces, then convert the string into an array and chunk it. Finally if merge every chunk and apply \n to each one.
var squareStr = function(str, chunk) {
str = str.replace(/ /g, '')
str = str.split('');
temp = []
for (i=0; i<str.length; i+=chunk)
temp.push(str.slice(i,i+chunk));
return temp.map(function(a){return a.join('')+"\n"}).join('')
}
console.log(squareStr('whatwonderfulday', 4));
console.log(squareStr('if life was easy god then god would not have given us brain to think', 8));

So many ways of doing that...
All other answers here are correct too, here's my approach, a more "readable" answer, using very basic recurses...
You have should at least tried...
I also have included a check to see if the string lenght is under 80.
var squareStr = function(str, charsPerLine) {
if (str.length > 80){
return;
}
str = str.replace(/ /g,'')
var stringSplited = str.split('');
var newString = '';
stringSplited.forEach(function(letter,index){
if (index % charsPerLine == 0 && newString.length > 0){
newString += '\n'; //IF YOU WANT TO USE IT IN THE HTML, USE '<br>' HERE
}
newString += letter;
});
console.log(newString);
return newString;
}
squareStr('whatwonderfulday', 4);
squareStr('if life was easy god then god would not have given us brain to think', 8);

Unless you're dealing with really long strings, I don't see a reason not to use replace to insert a newline every n characters:
function squareText(input) {
const inputNoSpaces = input.replace(/\s/g, '');
const partLen = Math.ceil(Math.sqrt(inputNoSpaces.length));
const replaceExpr = new RegExp(`.{1,${partLen}}`, 'g');
return inputNoSpaces.replace(replaceExpr, '$&\n');
}
const input = 'if life was easy then god would not have given us brain to think';
console.log(squareText(input));
This just calculates the line length and then creates a new RegExp that matches that many characters and uses it to replace each match with itself plus a newline.

Related

Looping through a String

I want to get every word that is shown after the word and.
var s = "you have a good day and time works for you and I'll make sure to
get the kids together and that's why I was asking you to do the needful and
confirm"
for (var  i= 0 ; i <= 3; i++){
 var body = s;
 var and = body.split("and ")[1].split(" ")[0];
 body = body.split("and ")[1].split(" ")[1];
 console.log(and);
}
How do I do this?!
Simplest thing is probably to use a regular expression looking for "and" followed by whitespace followed by the "word" after it, for instance something like /\band\s*([^\s]+)/g:
var s = "you have a good day and time works for you and I'll make sure to get the kids together and that's why I was asking you to do the needful and confirm";
var rex = /\band\s*([^\s]+)/g;
var match;
while ((match = rex.exec(s)) != null) {
console.log(match[1]);
}
You may well need to tweak that a bit (for instance, \b ["word boundary"] considers - a boundary, which you may not want; and separately, your definition of "word" may be different from [^\s]+, etc.).
at first you need to split the whole string in "and ", after that you have to split every element of given array into spaces, and the first element of the second given array will be the first word after the "and" word.
var s = "you have a good day and time works for you and I'll make sure to get the kids together and that's why I was asking you to do the needful and confirm"
var body = s;
var and = body.split("and ");
for(var i =0; i<and.length;i++){
console.log(and[i].split(" ")[0]);
}
You can split, check for "and" word, and get next one:
var s = "you have a good day and time works for you and I'll make sure to get the kids together and that's why I was asking you to do the needful and confirm";
var a = s.split(' ');
var cont = 0;
var and = false;
while (cont < a.length) {
if (and) {
console.log(a[cont]);
}
and = (a[cont] == 'and');
cont++;
}
Another way to do this using replace
var s = "you have a good day and time works for you and I'll make sure to get the kids together and that's why I was asking you to do the needful and confirm"
s.replace(/and\s+([^\s]+)/ig, (match, word) => console.log(word))

Javascript toArray to avoid cutting characters

I have a quick question.
This is my code, and problem with it is when i run some emojis thro this it displays them as ?, cause it cuts the emoji in half.
angular.module('Joe.filters').filter("initials", function() {
return function(string) {
if (string) {
var words = string.split(" ");
if (words.length) {
string = words[0].charAt(0);
if (words[1]) {
string += words[1].charAt(0);
}
}
}
return string;
};
});
Now, im thinking if i can solve this with toArray, and if yes, how?
Note: if i run in console the "fix" with array.
j = '📌';
"📌"
j.length
2
s = _.toArray(j)
["📌"]
s.length
1
Thanks in advance!!
In ES6, .charAt and [indexing] still work with 16-bit units, but String.iterator is aware of 32-bit chars. So, to extract the first char which is possibly beyond the plane 0, you have to force iteration on the string, for example:
word = '📌HELLO';
let b = [...word][0]
// or
let [c] = word
console.log(b, c)
Another option is to extract the first code point and convert it back to a character:
let a = String.fromCodePoint(word.codePointAt(0))
To answer the bonus question, I have this rather trivial function in my "standard repertoire"
let first = ([a]) => a
Using this func, your initials logic can be written as
let initials = str => str.split(' ').slice(0, 2).map(first).join('')

How to remove the blank lines in a textarea with JavaScript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I get the content of a textarea with:
var stringArray = document.getElementById('textarea').value;
I must remove all blank lines (even blank lines with spaces). What is an efficient way to do that?
EDIT: I want to remove the blank lines, not the whitespace.
e.g.
A
B
C
D
to
A
B
C
D
Finally I managed to make it work. This is the code just in case someone else would need it:
function delBlankLines() {
var stringArray = document.getElementById('textarea').value.split('\n');
var temp = [""];
var x = 0;
for (var i = 0; i < stringArray.length; i++) {
if (stringArray[i].trim() != "") {
temp[x] = stringArray[i];
x++;
}
}
temp = temp.join('\n');
document.myform.textarea.value = temp;
}
So, the textarea content is split into a string array, that array is looped and checked if the trimmed current line is blank; if it's not, the line is copied to a temporary string array (basically the blank lines are ignored). At the end, I update the textarea with the temporary string array.
you can use the native JavaScript trim method (available on the string prototype): textareaValue.trim().
Trivia: there's automatic setting of window.textarea to be document.getElementById('textarea'). So you can access that by just doing textarea. Therefore to access the textual content of the textarea you can use: textarea.innerHTML or const textAreaValue = textarea.value.
Next, run textAreaValue.trim(); this will get rid of any outer white space. " \n\n textArea \n\n\t\n " will turn into just "textArea".
Ok now we can split on new lines: const stringArray = textAreaValue.split('\n'). Since \n is the carriage return aka new line symbol.
Next, we'll want to skip any lines which have nothing but whitespace which we can probably find in a few ways but to be safest \S should work. To test out different regexes I recommend: regex101.com.
For a more modern version:
textarea.value = `
the
quick
brown
fox
jumped
over the lazy
dog.
`;
/*
function oldSolution() {
var cleanedString = '';
console.log(textarea.value);
var stringArray = textarea.value.trim().split('\n');
for(var i = 0; i < stringArray.length; i++){
var line = stringArray[i];
if(line.match('/\S/') !== -1){
cleanedString += line.trim();
}
}
console.log(cleanedString);
output.innerText = cleanedString;
return cleanedString;
}
*/
const cleanText = () => {
const stringArray = textarea.value
.trim()
.split('\n')
.filter(line => /\S/.test(line));
console.log({stringArray})
const cleanedString = stringArray.map(line => line.trim()).join(' ');
console.log(cleanedString);
output.innerText = cleanedString;
return cleanedString;
}
<textarea rows='5' cols='50' id='textarea'></textarea>
<input type='button' value='Extract Text' onclick='cleanText()'/>
<div id="output"></div>

Finding the difference between two string in Javascript with regex [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Regex experts please help to see if this problem can be solved by regex:
Given string 1 is any string
And string 2 is any string containing all parts of string 1 (but not a simple match -- I will give example)
How to use regex to replace all parts of string 1 in string 2 with blank so that what's remained is the string not in string 1?
For example:
str1 = "test xyz";
str2 = "test ab xyz"
I want " ab" or "ab " back. What is the regex I can write so that when I run a replace function on str2, it will return " ab"?
Here is some non-regex code:
function findStringDiff(str1, str2) {
var compareString = function(str1, str2) {
var a1 = str1.split("");
var a2 = str2.split("");
var idx2 = 0;
a1.forEach(function(val) {
if (a2[idx2] === val) {
a2.splice(idx2,1);
} else {
idx2 += 1;
}
});
if (idx2 > 0) {
a2.splice(idx2,a2.length);
}
return a2.join("");
}
if (str1.length < str2.length) {
return compareString(str1, str2);
} else {
return compareString(str2, str1);
}
}
console.log(findStringDiff("test xyz","test ab xyz"));
Regexes only recognize if a string matches a certain pattern. They're not flexible enough to do comparisons like you're asking for. You would have to take the first string and build a regular language based on it to recognize the second string, and then use match groups to grab the other parts of the second string and concatenate them together. Here's something that does what I think you want in a readable way.
//assuming "b" contains a subsequence containing
//all of the letters in "a" in the same order
function getDifference(a, b)
{
var i = 0;
var j = 0;
var result = "";
while (j < b.length)
{
if (a[i] != b[j] || i == a.length)
result += b[j];
else
i++;
j++;
}
return result;
}
console.log(getDifference("test fly", "test xy flry"));
Here's a jsfiddle for it: http://jsfiddle.net/d4rcuxw9/1/
I find this question really interesting. Even though I'm a little late, I would like to share my solution on how to accomplish this with regex. The solution is concise but not very readable.
While I like it for its conciseness, I probably would not use it my code, because it's opacity reduces the maintainability.
var str1 = "test xyz",
str2 = "test ab xyz"
replacement = '';
var regex = new RegExp(str1.split('').map(function(char){
return char.replace(/[.(){}+*?[|\]\\^$]/, '\\$&');
}).join('(.*)'));
if(regex.test(str2)){
for(i=1; i<str1.length; i++) replacement = replacement.concat('$' + i);
var difference = str2.replace(regex, replacement);
} else {
alert ('str2 does not contain str1');
}
The regular expression for "test xyz" is /t(.*)e(.*)s(.*)t(.*) (.*)x(.*)y(.*)z/ and replacement is "$1$2$3$4$5$6$7".
The code is no longer concise, but it works now even if str1 contains special characters.
To find out if there are extra '.' like you are asking for, you can do this:
result = "$1...00".match(/\$1\.(\.*)?00/)[1];
result is then the EXTRA '.'s found. You cannot use regex to compare strings using only regex. Perhaps use this, then compare the results.
You can also try this:
result = "$1...00".match(/(\$)(\d+)\.(\.*)?(\d+)/);
// Outputs: ["$1...00", "$", "1", "..", "00"]
Which will extract the various parts to compare.
If you are only concerned with testing whether a given string contains two or more sequential dot '.' characters:
var string = '$1..00',
regexp = /(\.\.+)/;
alert('Is this regular expression ' + regexp + ' found in this string ' + string + '?\n\n' + regexp.test(string) + '\n\n' + 'Match and captures: ' + regexp.exec(string));
If you need it to match the currency format:
var string = '$1..00',
regexp = /\$\d*(\.\.+)(?:\d\d)+/;
alert('Is this regular expression ' + regexp + ' found in this string ' + string + '?\n\n' + regexp.test(string) + '\n\n' + 'Match and captures: ' + regexp.exec(string));
But I caution you that Regular Expressions aren't for comparing the differences between two strings; they are used for defining patterns to match against given strings.
So, while this may directly answer how to find the "multiple dots" pattern, it is useless for "finding the difference between two strings".
The StackOverflow tag wiki provides an excellent overview and basic reference for RegEx. See: https://stackoverflow.com/tags/regex/info

Regex : split string based on first occurrence, with occurance [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I am terrible at regex. Please have pity and give me a hand.
I am trying to split a string by the first occurrence of And (case sensitive), into an array with a length of 2. I have no idea were to begin, so can someone help me?
var strArr = "Thing And other thing".split(/magic regex/);
expect(strArr).to.deep.equal(["Thing","And other thing"]);
var strArr = "Thing and other thing".split(/magic regex/);
expect(strArr).to.deep.equal(["Thing and other thing", ""]);
var strArr = "One Thing And other thing And yet another thing".split(/magic regex/);
expect(strArr).to.deep.equal(["One Thing","And other thing And yet another thing"]);
var strArr = "yep, just one thing".split(/magic regex/);
expect(strArr).to.deep.equal(["yep, just one thing", ""]);
UPDATE this is working exactly the way I need it to, but its still ugly:
parser = function(str) {
var spl;
spl = str.split(/\s(?=And )/);
if (spl.length > 1) {
spl = [spl.shift(), spl.join(" ")];
} else {
spl = [str, ''];
}
return spl;
};
There is no need for a regular expression for that. Just get the first index of "And" in the string:
var i = str.indexOf("And");
var strArr;
if (i == -1) {
strArr = [ str ];
} else {
strArr = [ str.substr(0, i), str.substr(i) ];
}
While Guffa's method works, if you end up needing to do this the regex way, the following will work (via a positive lookahead):
var str = "Thing And other thing";
var spl = str.split(/\s(?=And\s)/);
if (spl.length > 1)
spl = [spl.shift(), spl.join(" ")];
To test:
alert(JSON.stringify(spl));
jsFiddle
Updated to ensure it splits on [space]And[space]
I suggest doing a simple split then checking if the array has one or two
strArr.split("And", 2).length;

Categories

Resources