Regex/Javascript, convert strings with absolute values |x| to abs(x) - javascript

I'm trying to convert some math related strings containing absolute values, using Regex in Javascript.
I would like to convert all occurences of |foo| to abs(foo).
How can I detect if the character is opening or closing, given that they could also be nested?
Basically I would like to convert all occurrences of opening | to abs( and all closing | to ). Whatever is between the vertical bars is unchanged.
Some examples of possible input and desired output:
|x|+12 abs(x)+12
|x|+12+|x+2| abs(x)+12+abs(x+2)
|x|+|x+|z|| abs(x)+abs(x+abs(z))
Any ideas?

There are regex dialects that support nesting, JavaScript is not one of them. You can however do this in steps:
tag the |s with nesting level (+1, -1, as you go from left to right)
identify start and end | of same level from left to right based on tags, and from lowest level to highest level
clean up left over tags in case of unbalanced input
Functional code with test cases up to 3 levels (the code works to any level) :
function fixAbs(str) {
const startTag = '{{s%L%}}';
const endTag = '{{e%L%}}';
const absRegex = /\{\{s(\d+)\}\}(.*?)\{\{e\1\}\}/g;
let level = 0;
str = str
.replace(/ /g, '') // remove all spaces
.replace(/(\|*)?(\w+)(\|*)?/g, function(m, c1, c2, c3) {
// regex matches variables with all leading and trailing `|`s
let s = c2;
if(c1) {
// add a start tag to each leading `|`: `{{s0}}`, `{{s1}}`, ...
// and post-increase level
s = '';
for(let i = 0; i < c1.length; i++) {
s += startTag.replace(/%L%/, level++);
}
s += c2;
}
if(c3) {
// decrease level,
// and add a end tag to each trailing `|`: `{{e2}}`, `{{e1}}`, ...
for(let i = 0; i < c3.length; i++) {
s += endTag.replace(/%L%/, --level);
}
}
return s;
});
// find matching start and end tag from left to right,
// repeat for each level
while(str.match(absRegex)) {
str = str.replace(absRegex, function(m, c1, c2, c3) {
return 'abs(' + c2 + ')';
});
}
// clean up tags in case of unbalanced input
str = str.replace(/\{\{[se]-?\d+\}\}/g, '|');
return str;
}
const testCases = [
'|x|+12',
'|x|+|y+|z||',
'|x|+||y|+z|',
'|x|+|x+|y|+z|',
'|x|+|x+|y+|t||+z|',
'|x|+12+|2+x|',
'|x|+12+|x+2|'
].forEach(str => {
let result = fixAbs(str);
console.log('"' + str + '" ==> "' + result + '"');
});
Output:
"|x|+12" ==> "abs(x)+12"
"|x|+|y+|z||" ==> "abs(x)+abs(y+abs(z))"
"|x|+||y|+z|" ==> "abs(x)+abs(abs(y)+z)"
"|x|+|x+|y|+z|" ==> "abs(x)+abs(x+abs(y)+z)"
"|x|+|x+|y+|t||+z|" ==> "abs(x)+abs(x+abs(y+abs(t))+z)"
"|x|+12+|2+x|" ==> "abs(x)+12+abs(2+x)"
"|x|+12+|x+2|" ==> "abs(x)+12+abs(x+2)"
Code is annotated with comments for clarity.
This is based on a TWiki blog at https://twiki.org/cgi-bin/view/Blog/BlogEntry201109x3

Related

removing the second matched word from a string?

I got a string
For example:
This is for trails and I want to learn Js and Coding and Development
The above mentioned line as a string
function trail(sen){
var cat = "and"
var fin = sen.indexOf(cat);
if(fin > 0){
var last = sen.substring(0, fin)
}
else{
var last = sen;
}
return last;
}
console.log(
trail("This is for trails and I want to learn Js and Coding and Development ")
);
I am trying to find the index of the second "and" in a string rather than the first one.
and get the string part from index 0 to that second "and"
Could you please provide the better approach ?
You can use split together with join to achieve this, like so:
const myStr = 'This is for trails and I want to learn Js and Coding and Development'
const subStr = 'and'
const splitted = getSplitted(myStr, subStr, 2) // Splits before the "N th" ocurrence of subStr
console.log(splitted)
function getSplitted(str, subStr, idx) {
return str.split(subStr, idx).join(subStr);
}
You can first find the second occurrence and then remove it via simple slice.
This method also supports regular expressions as pattern.
/**
* Find the n-th occurrence of given pattern in a string.
* #param { string } str The string to be examined.
* #param { string | RegExp } pattern The pattern to be matched.
* #param { number } n Starting index.
* #return { [number, string | RegExpExecArray] } The index & the match result. `[-1, null]` if pattern occurs less than n times.
*/
function findNth(str, pattern, n = 1) {
// The total processed index & and the last match
let index = 0, result;
for(; n--; ) {
// Index of the next match relative to the end of the last one
let offset = -1;
if(pattern instanceof RegExp) {
const match = pattern.exec(str);
if(match !== null) {
offset = match.index;
result = match[0];
}
}
else { // string case
offset = str.indexOf(pattern);
result = pattern;
}
// If none is matched
if(offset === -1)
return [-1, null];
// Seek over the match result
offset += result.length;
str = str.slice(offset);
index += offset;
}
// Gotta go back to the start of the last match
index -= result.length;
return [index, result];
}
/** Remove the n-th occurrence of given pattern out of a string. */
function removeNth(str, pattern, n = 1) {
const result = findNth(str, pattern, n);
if(result[0] === -1)
return str;
return str.slice(0, result[0]) + str.slice(result[0] + result[1].length);
}
{
const str = 'This is for trails and I want to learn Js and Coding and Development';
console.log(removeNth(str, 'and', 2));
console.log(removeNth(str, /\s*and/, 2));
}
Use split
sen.split(cat, 2) // This line will divide the syntax into an array of two elements till second "and" occurrence
// ['This is for trails ', ' I want to learn Js ']
Then you need to join them to add the first and
sen.split(cat, 2).join(cat)
And to get the length
sen.split(cat, 2).join(cat).length
let str = "This is for trails and I want to learn Js and Coding and Development".split("and", 2).join("");
console.log(str);

How can I use a Regular Expression to replace everything except specific words in a string with Javascript

Imagine you have a string like this: "This is a sentence with words."
I have an array of words like $wordList = ["sentence", "words"];
I want to highlight words that aren't on the list. Which means I need to find and replace everything else and I can't seem to crack how to do that (if it's possible) with RegEx.
If I want to match the words I can do something like:
text = text.replace(/(sentence|words)\b/g, '<mark>$&</mark>');
(which will wrap the matching words in "mark" tags and, assuming I have some css for <mark>, highlight them) which works perfectly. But I need the opposite! I need it to basically select the entire string and then exclude the words listed. I've tried /^((?!sentence|words)*)*$/gm but this gives me a strange infinity issue because I think it's too open ended.
Taking that original sentence, what I would hope to end up with is "<mark> This is a </mark> sentence <mark> with some </mark> words."
Basically wrapping (via replace) everything except the words listed.
The closest I can seem to get is something like /^(?!sentence|words).*\b/igm which will successfully do it if a line starts with one of the words (ignoring that entire line).
So to summarize: 1) Take a string 2) take a list of words 3) replace everything in the string except the list of words.
Possible? (jQuery is loaded for something else already, so raw JS or jQuery are both acceptable).
Create the regex from the word list.
Then do a string replace with the regex.
(It's a tricky regex)
var wordList = ["sentence", "words"];
// join the array into a string using '|'.
var str = wordList.join('|');
// finalize the string with a negative assertion
str = '\\W*(?:\\b(?!(?:' + str + ')\\b)\\w+\\W*|\\W+)+';
//create a regex from the string
var Rx = new RegExp( str, 'g' );
console.log( Rx );
var text = "%%%555This is a sentence with words, but not sentences ?!??!!...";
text = text.replace( Rx, '<mark>$&</mark>');
console.log( text );
Output
/\W*(?:\b(?!(?:sentence|words)\b)\w+\W*|\W+)+/g
<mark>%%%555This is a </mark>sentence<mark> with </mark>words<mark>, but not sentences ?!??!!...</mark>
Addendum
The regex above assumes the word list contains only word characters.
If that's not the case, you must match the words to advance the match position
past them. This is easily accomplished with a simplified regex and a callback function.
var wordList = ["sentence", "words", "won't"];
// join the array into a string using '|'.
var str = wordList.join('|');
str = '([\\S\\s]*?)(\\b(?:' + str + ')\\b|$)';
//create a regex from the string
var Rx = new RegExp( str, 'g' );
console.log( Rx );
var text = "%%%555This is a sentence with words, but won't be sentences ?!??!!...";
// Use a callback to insert the 'mark'
text = text.replace(
Rx,
function(match, p1,p2)
{
var retStr = '';
if ( p1.length > 0 )
retStr = '<mark>' + p1 + '</mark>';
return retStr + p2;
}
);
console.log( text );
Output
/([\S\s]*?)(\b(?:sentence|words|won't)\b|$)/g
<mark>%%%555This is a </mark>sentence<mark> with </mark>words<mark>, but
</mark>won't<mark> be sentences ?!??!!...</mark>
You could still perform the replacement on the positive matches, but reverse the closing/opening tag, and add an opening tag at the start and a closing one at the end of the string. I use here your regular expression which could be anything you want, so I'll assume it matches correctly what needs to be matched:
var text = "This is a sentence with words.";
text = "<mark>" + text.replace(/\b(sentence|words)\b/g, '</mark>$&<mark>') + "</mark>";
// If empty tags bother you, you can add:
text = text.replace(/<mark><\/mark>/g, "");
console.log(text);
Time Complexity
In comments below someone makes a point that the second replacement (which is optional) is a waste of time. But it has linear time complexity as is illustrated in the following snippet which charts the duration for increasing string sizes.
The X axis represents the number of characters in the input string, and the Y-axis represents the number of milliseconds it takes to execute the replacement with /<mark><\/mark>/g on such input string:
// Reserve memory for the longest string
const s = '<mark></mark>' + '<mark>x</mark>'.repeat(2000);
regex = /<mark><\/mark>/g,
millisecs = {};
// Collect timings for several string sizes:
for (let size = 100; size < 25000; size+=100) {
millisecs[size] = test(15, 8, _ => s.substr(0, size).replace(regex, ''));
}
// Show results in a chart:
chartFunction(canvas, millisecs, "len", "ms");
// Utilities
function test(countPerRun, runs, f) {
let fastest = Infinity;
for (let run = 0; run < runs; run++) {
const started = performance.now();
for (let i = 0; i < countPerRun; i++) f();
// Keep the duration of the fastest run:
fastest = Math.min(fastest, (performance.now() - started) / countPerRun);
}
return fastest;
}
function chartFunction(canvas, y, labelX, labelY) {
const ctx = canvas.getContext('2d'),
axisPix = [40, 20],
largeY = Object.values(y).sort( (a, b) => b - a )[
Math.floor(Object.keys(y).length / 10)
] * 1.3; // add 30% to value at the 90th percentile
max = [+Object.keys(y).pop(), largeY],
coeff = [(canvas.width-axisPix[0]) / max[0], (canvas.height-axisPix[1]) / max[1]],
textAlignPix = [-8, -13];
ctx.translate(axisPix[0], canvas.height-axisPix[1]);
text(labelY + "/" + labelX, [-5, -13], [1, 1], false, 2);
// Draw axis lines
for (let dim = 0; dim < 2; dim++) {
const c = coeff[dim], world = [c, 1];
let interval = 10**Math.floor(Math.log10(60 / c));
while (interval * c < 30) interval *= 2;
if (interval * c > 60) interval /= 2;
let decimals = ((interval+'').split('.')[1] || '').length;
line([[0, 0], [max[dim], 0]], world, dim);
for (let x = 0; x <= max[dim]; x += interval) {
line([[x, 0], [x, -5]], world, dim);
text(x.toFixed(decimals), [x, textAlignPix[1-dim]], world, dim, dim+1);
}
}
// Draw function
line(Object.entries(y), coeff);
function translate(coordinates, world, swap) {
return coordinates.map( p => {
p = [p[0] * world[0], p[1] * world[1]];
return swap ? p.reverse() : p;
});
}
function line(coordinates, world, swap) {
coordinates = translate(coordinates, world, swap);
ctx.beginPath();
ctx.moveTo(coordinates[0][0], -coordinates[0][1]);
for (const [x, y] of coordinates.slice(1)) ctx.lineTo(x, -y);
ctx.stroke();
}
function text(s, p, world, swap, align) { // align: 0=left,1=center,2=right
const [[x, y]] = translate([p], world, swap);
ctx.font = '9px courier';
ctx.fillText(s, x - 2.5*align*s.length, 2.5-y);
}
}
<canvas id="canvas" width="600" height="200"></canvas>
For each string size (which is incremented with steps of 100 characters), the time to run the regex 15 times is measured. This measurement is repeated 8 times and the duration of the fastest run is reported in the graph. On my PC the regex runs in 25µs on a string with 25 000 characters (consisting of <mark> tags). So not something to worry about ;-)
You may see some spikes in the chart (due to browser and OS interference), but the overall tendency is linear.
Given that the main regex has linear time complexity, the overall time complexity is not negatively affected by it.
However that optional part can be performed without regular expression as follows:
if (text.substr(6, 7) === '</mark>') text = text.substr(13);
if (text.substr(-13, 6) === '<mark>') text = text.substr(0, text.length-13);
Due to how JavaScript engines deal with strings (immutable), this longer code runs in constant time.
Of course, it does not change the overall time complexity, which remains linear.
I'm not sure if this will work for every case, but for the given string it does.
let s1 = "This is a sentence with words.";
let wordList = ["sentence", "words"];
let reg = new RegExp("([\\s\\S]*?)(" + wordList.join("|") + ")", "g");
console.log(s1.replace(reg, "<mark>$1</mark>$2"))
Do it the opposite way: Mark everything and unmark the matched words you have.
text = `<mark>${text.replace(/\b(sentence|words)\b/g, '</mark>$&<mark>')}</mark>`;
Negated regex is possible but inefficient for this. In fact regex is not the right tool. The viable method is to go through the strings and manually construct the end string:
//var text = "This is a sentence with words.";
//var wordlist = ["sentence", "words"];
var result = "";
var marked = false;
var nextIndex = 0;
while (nextIndex != -1) {
var endIndex = text.indexOf(" ", nextIndex + 1);
var substring = text.slice(nextIndex, endIndex == -1 ? text.length : endIndex);
var contains = wordlist.some(word => substring.includes(word));
if (!contains && !marked) {
result += "<mark>";
marked = true;
}
if (contains && marked) {
result += "</mark>";
marked = false;
}
result += substring;
nextIndex = endIndex;
}
if (marked) {
result += "</mark>";
}
text = result;

How can I split a string into a given number of lines?

Here is my question:
Given a string, which is made up of space separated words, how can I split that into N strings of (roughly) even length, only breaking on spaces?
Here is what I've gathered from research:
I started by researching word-wrapping algorithms, because it seems to me that this is basically a word-wrapping problem. However, the majority of what I've found so far (and there is A LOT out there about word wrapping) assumes that the width of the line is a known input, and the number of lines is an output. I want the opposite.
I have found a (very) few questions, such as this that seem to be helpful. However, they are all focused on the problem as one of optimization - e.g. how can I split a sentence into a given number of lines, while minimizing the raggedness of the lines, or the wasted whitespace, or whatever, and do it in linear (or NlogN, or whatever) time. These questions seem mostly to be unanswered, as the optimization part of the problem is relatively "hard".
However, I don't care that much about optimization. As long as the lines are (in most cases) roughly even, I'm fine if the solution doesn't work in every single edge case, or can't be proven to be the least time complexity. I just need a real world solution that can take a string, and a number of lines (greater than 2), and give me back an array of strings that will usually look pretty even.
Here is what I've come up with:
I think I have a workable method for the case when N=3. I start by putting the first word on the first line, the last word on the last line, and then iteratively putting another word on the first and last lines, until my total width (measured by the length of the longest line) stops getting shorter. This usually works, but it gets tripped up if your longest words are in the middle of the line, and it doesn't seem very generalizable to more than 3 lines.
var getLongestHeaderLine = function(headerText) {
//Utility function definitions
var getLongest = function(arrayOfArrays) {
return arrayOfArrays.reduce(function(a, b) {
return a.length > b.length ? a : b;
});
};
var sumOfLengths = function(arrayOfArrays) {
return arrayOfArrays.reduce(function(a, b) {
return a + b.length + 1;
}, 0);
};
var getLongestLine = function(lines) {
return lines.reduce(function(a, b) {
return sumOfLengths(a) > sumOfLengths(b) ? a : b;
});
};
var getHeaderLength = function(lines) {
return sumOfLengths(getLongestLine(lines));
}
//first, deal with the degenerate cases
if (!headerText)
return headerText;
headerText = headerText.trim();
var headerWords = headerText.split(" ");
if (headerWords.length === 1)
return headerText;
if (headerWords.length === 2)
return getLongest(headerWords);
//If we have more than 2 words in the header,
//we need to split them into 3 lines
var firstLine = headerWords.splice(0, 1);
var lastLine = headerWords.splice(-1, 1);
var lines = [firstLine, headerWords, lastLine];
//The header length is the length of the longest
//line in the header. We will keep iterating
//until the header length stops getting shorter.
var headerLength = getHeaderLength(lines);
var lastHeaderLength = headerLength;
while (true) {
//Take the first word from the middle line,
//and add it to the first line
firstLine.push(headerWords.shift());
headerLength = getHeaderLength(lines);
if (headerLength > lastHeaderLength || headerWords.length === 0) {
//If we stopped getting shorter, undo
headerWords.unshift(firstLine.pop());
break;
}
//Take the last word from the middle line,
//and add it to the last line
lastHeaderLength = headerLength;
lastLine.unshift(headerWords.pop());
headerLength = getHeaderLength(lines);
if (headerLength > lastHeaderLength || headerWords.length === 0) {
//If we stopped getting shorter, undo
headerWords.push(lastLine.shift());
break;
}
lastHeaderLength = headerLength;
}
return getLongestLine(lines).join(" ");
};
debugger;
var header = "an apple a day keeps the doctor away";
var longestHeaderLine = getLongestHeaderLine(header);
debugger;
EDIT: I tagged javascript, because ultimately I would like a solution I can implement in that language. It's not super critical to the problem though, and I would take any solution that works.
EDIT#2: While performance is not what I'm most concerned about here, I do need to be able to perform whatever solution I come up with ~100-200 times, on strings that can be up to ~250 characters long. This would be done during a page load, so it needs to not take forever. For example, I've found that trying to offload this problem to the rendering engine by putting each string into a DIV and playing with the dimensions doesn't work, since it (seems to be) incredibly expensive to measure rendered elements.
Try this. For any reasonable N, it should do the job:
function format(srcString, lines) {
var target = "";
var arr = srcString.split(" ");
var c = 0;
var MAX = Math.ceil(srcString.length / lines);
for (var i = 0, len = arr.length; i < len; i++) {
var cur = arr[i];
if(c + cur.length > MAX) {
target += '\n' + cur;
c = cur.length;
}
else {
if(target.length > 0)
target += " ";
target += cur;
c += cur.length;
}
}
return target;
}
alert(format("this is a very very very very " +
"long and convoluted way of creating " +
"a very very very long string",7));
You may want to give this solution a try, using canvas. It will need optimization and is only a quick shot, but I think canvas might be a good idea as you can calculate real widths. You can also adjust the font to the really used one, and so on. Important to note: This won't be the most performant way of doing things. It will create a lot of canvases.
DEMO
var t = `However, I don't care that much about optimization. As long as the lines are (in most cases) roughly even, I'm fine if the solution doesn't work in every single edge case, or can't be proven to be the least time complexity. I just need a real world solution that can take a string, and a number of lines (greater than 2), and give me back an array of strings that will usually look pretty even.`;
function getTextTotalWidth(text) {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.font = "12px Arial";
ctx.fillText(text,0,12);
return ctx.measureText(text).width;
}
function getLineWidth(lines, totalWidth) {
return totalWidth / lines ;
}
function getAverageLetterSize(text) {
var t = text.replace(/\s/g, "").split("");
var sum = t.map(function(d) {
return getTextTotalWidth(d);
}).reduce(function(a, b) { return a + b; });
return sum / t.length;
}
function getLines(text, numberOfLines) {
var lineWidth = getLineWidth(numberOfLines, getTextTotalWidth(text));
var letterWidth = getAverageLetterSize(text);
var t = text.split("");
return createLines(t, letterWidth, lineWidth);
}
function createLines(t, letterWidth, lineWidth) {
var i = 0;
var res = t.map(function(d) {
if (i < lineWidth || d != " ") {
i+=letterWidth;
return d;
}
i = 0;
return "<br />";
})
return res.join("");
}
var div = document.createElement("div");
div.innerHTML = getLines(t, 7);
document.body.appendChild(div);
I'm sorry this is C#. I had created my project already when you updated your post with the Javascript tag.
Since you said all you care about is roughly the same line length... I came up with this. Sorry for the simplistic approach.
private void DoIt() {
List<string> listofwords = txtbx_Input.Text.Split(' ').ToList();
int totalcharcount = 0;
int neededLineCount = int.Parse(txtbx_LineCount.Text);
foreach (string word in listofwords)
{
totalcharcount = totalcharcount + word.Count(char.IsLetter);
}
int averagecharcountneededperline = totalcharcount / neededLineCount;
List<string> output = new List<string>();
int positionsneeded = 0;
while (output.Count < neededLineCount)
{
string tempstr = string.Empty;
while (positionsneeded < listofwords.Count)
{
tempstr += " " + listofwords[positionsneeded];
if ((positionsneeded != listofwords.Count - 1) && (tempstr.Count(char.IsLetter) + listofwords[positionsneeded + 1].Count(char.IsLetter) > averagecharcountneededperline))//if (this is not the last word) and (we are going to bust the average)
{
if (output.Count + 1 == neededLineCount)//if we are writting the last line
{
//who cares about exceeding.
}
else
{
//we're going to exceed the allowed average, gotta force this loop to stop
positionsneeded++;//dont forget!
break;
}
}
positionsneeded++;//increment the needed position by one
}
output.Add(tempstr);//store the string in our list of string to output
}
//display the line on the screen
foreach (string lineoftext in output)
{
txtbx_Output.AppendText(lineoftext + Environment.NewLine);
}
}
(Adapted from here, How to partition an array of integers in a way that minimizes the maximum of the sum of each partition?)
If we consider the word lengths as a list of numbers, we can binary search the partition.
Our max length ranges from 0 to sum (word-length list) + (num words - 1), meaning the spaces. mid = (range / 2). We check if mid can be achieved by partitioning into N sets in O(m) time: traverse the list, adding (word_length + 1) to the current part while the current sum is less than or equal to mid. When the sum passes mid, start a new part. If the result includes N or less parts, mid is achievable.
If mid can be achieved, try a lower range; otherwise, a higher range. The time complexity is O(m log num_chars). (You'll also have to consider how deleting a space per part, meaning where the line break would go, features into the calculation.)
JavaScript code (adapted from http://articles.leetcode.com/the-painters-partition-problem-part-ii):
function getK(arr,maxLength) {
var total = 0,
k = 1;
for (var i=0; i<arr.length; i++) {
total += arr[i] + 1;
if (total > maxLength) {
total = arr[i];
k++;
}
}
return k;
}
function partition(arr,n) {
var lo = Math.max(...arr),
hi = arr.reduce((a,b) => a + b);
while (lo < hi) {
var mid = lo + ((hi - lo) >> 1);
var k = getK(arr,mid);
if (k <= n){
hi = mid;
} else{
lo = mid + 1;
}
}
return lo;
}
var s = "this is a very very very very "
+ "long and convoluted way of creating "
+ "a very very very long string",
n = 7;
var words = s.split(/\s+/),
maxLength = partition(words.map(x => x.length),7);
console.log('max sentence length: ' + maxLength);
console.log(words.length + ' words');
console.log(n + ' lines')
console.log('')
var i = 0;
for (var j=0; j<n; j++){
var str = '';
while (true){
if (!words[i] || str.length + words[i].length > maxLength){
break
}
str += words[i++] + ' ';
}
console.log(str);
}
Using the Java String Split() Method to split a string we will discover How and Where to Apply This String Manipulation Technique:
We'll examine the Java Split() method's explanation and discover how to apply it. The principles are explained simply and with enough programming examples, either as a separate explanation or in the comment part of the programs.
The Java String Split() method is used to divide or split the calling Java String into pieces and return the Array, as the name implies. The delimiters("", " ", ) or regular expressions that we have supplied separately for each component or item of an array.
Syntax
String[ ] split(String regExp)
First Case: It involves initializing a Java String variable with a variety of words separated by spaces, using the Java String Split() method, and evaluating the results. We can effectively print each word without the space using the Java Split() function.
Second Case: In this case, we initialize a Java String variable and attempt to split or deconstruct the main String variable to use the String Split() method utilizing a substring of the initialized String variable.
Third Case: In this case, we will attempt to split a String using its character by taking a String variable (a single word).
You can check out other approaches to this problem on YouTube and even coding websites on google such as Coding Ninjas
This old question was revived by a recent answer, and I think I have a simpler technique than the answers so far:
const evenSplit = (text = '', lines = 1) => {
if (lines < 2) {return [text]}
const baseIndex = Math .round (text .length / lines)
const before = text .slice (0, baseIndex) .lastIndexOf (' ')
const after = text .slice (baseIndex) .indexOf (' ') + baseIndex
const index = after - baseIndex < baseIndex - before ? after : before
return [
text .slice (0, index),
... evenSplit (text .slice (index + (before > -1 ? 1 : 0)), lines - 1)
]
}
const text = `However, I don't care that much about optimization. As long as the lines are (in most cases) roughly even, I'm fine if the solution doesn't work in every single edge case, or can't be proven to be the least time complexity. I just need a real world solution that can take a string, and a number of lines (greater than 2), and give me back an array of strings that will usually look pretty even.`
const display = (lines) => console .log (lines .join ('\n'))
display (evenSplit (text, 7))
display (evenSplit (text, 5))
display (evenSplit (text, 12))
display (evenSplit (`this should be three lines, but it has a loooooooooooooooooooooooooooooooong word`, 3))
.as-console-wrapper {max-height: 100% !important; top: 0}
It works by finding the first line then recurring on the remaining text with one fewer lines. The recursion bottoms out when we have a single line. To calculate the first line, we take an initial target index which is just an equal share of the string based on its length and the number of lines. We then check to find the closest space to that index, and split the string there.
It does no optimization, and could certainly be occasionally misled by long words, but mostly it just seems to work.

How to add newline after a repeating pattern

Assume that there is a string like this:
var content = "1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20";
I want to add <br /> after every 5 dots.
So, the result should be:
1.2.3.4.5.<br />
6.7.8.9.10.<br />
11.12.13.14.15.<br />
16.17.18.19.20.<br />
I want to do this without a for loop. Is it possible with just regex?
i'm doing this with this code;
regenerate:function(content,call){
var data2;
var brbr = content.replace(/[\u0250-\ue007]/g, '').match(/(\r\n)/g);
if (brbr !== "") {
data2 = content.replace(/[\u0250-\ue007]/g, '').replace(/(\r\n)/gm, "<br><br>");
} else {
data2 = content.replace(/[\u0250-\ue007]/g, '');
}
var dataArr = data2.split(".");
for (var y = 10; y < dataArr.length - 10; y += 10) {
var dataArrSpecific1 = dataArr[y] + ".";
var dataArrSpecific2 = dataArr[y] + ".<br>";
var dataArrSpecificBosluk = dataArr[y + 1];
var data3 = data2.replace(new RegExp(dataArrSpecific1.replace(/[\u0250-\ue007]/g, ''), "g"), "" + dataArrSpecific2.replace(/[\u0250-\ue007]/g, '') + "");
data3 = data3.replace(new RegExp(dataArrSpecificBosluk.replace(/[\u0250-\ue007]/g, ''), "g"), " " + dataArrSpecificBosluk.replace(/[\u0250-\ue007]/g, '') + "");
data2 = data3;
}
call(data2.replace(/[\u0250-\ue007]/g, ''));
}
Actually , i want to refactoring this code
Working bin:http://jsbin.com/dikifipelo/1/
var string = "1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20." ;
string = string.replace(/(([^\.]+\.){5})/g, "$1<br/>");
Works with any type and length of characters between the dots.
Explanation:
The pattern /(([^.]+.){5})/g can be broken down as such:
[^\.] - any character that is not a dot
[^\.]+ - any character that is not a dot, one or more times
[^\.]+\. - any character that is not a dot, one or more times, followed by a dot
([^\.]+\.){5} - any character....dot, appearing five times
(([^\.]+\.){5}) - any...five times, capture this (all round brackets capture unless told not to, with a ?: as the first thing inside them)
the /g/ flag makes it so that the whole string is matched - ie, all matches are found
"$1" represents the results of the first group (or bracket)
so, the replace function finds all instances of the pattern in the string, and replaces them with the match itself + a line break (br).
Once you learn regular expressions, life is never the same.

String that contains all ascii characters

I want to create a string in JavaScript that contains all ascii characters. How can I do this?
var s = ' !"#$%&\'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~';
My javascript is a bit rusty, but something like this:
s = '';
for( var i = 32; i <= 126; i++ )
{
s += String.fromCharCode( i );
}
Not sure if the range is correct though.
Edit:
Seems it should be 32 to 127 then. Adjusted.
Edit 2:
Since char 127 isn't a printable character either, we'll have to narrow it down to 32 <= c <= 126, in stead of 32 <= c <= 127.
Just loop the character codes and convert each to a character:
var s = '';
for (var i=32; i<=127;i++) s += String.fromCharCode(i);
Just wanted to put this here for reference. (takes about 13/100 to 26/100 of a ms on my computer to generate).
var allAsciiPrintables = JSON.stringify((Array.from(Array(126 + 32).keys()).slice(32).map((item) => {
return String.fromCharCode(item);
})).join(''));
Decomposed:
var allAsciiPrintables = (function() {
/* ArrayIterator */
var result = Array(126 + 32).keys();
/* [0, 126 + 32] */
result = Array.from(result);
/* [32, 126 + 32] */
result = result.slice(32);
/* transform each item from Number to its ASCII as String. */
result = result.map((item) => {
return String.fromCharCode(item);
});
/* convert from array of each string[1] to a single string */
result = result.join('');
/* create an escaped string so you can replace this code with the string
to avoid having to calculate this on each time the program runs */
result = JSON.stringify(result);
/* return the string */
return result;
})();
The most efficient solution(if you do want to generate the whole set each time the script runs, is probably)(takes around 3/100-35/100 of a millisecond on my computer to generate).
var allAsciiPrintables = (() => {
var result = new Array(126-32);
for (var i = 32; i <= 126; ++i) {
result[i - 32] = (String.fromCharCode(i));
}
return JSON.stringify(result.join(''));
})();
strangely, this is only 3-10 times slower than assigning the string literal directly(with backticks to tell javascript to avoid most backslash parsing).
var x;
var t;
t = performance.now();
x = '!\"#$%&\'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~';
t = performance.now() - t;
console.log(t);
.
This is a version written in python. Gives all ASCII characters in order as a single string.
all_ascii = ''.join(chr(k) for k in range(128)) # 7 bits
all_chars = ''.join(chr(k) for k in range(256)) # 8 bits
printable_ascii = ''.join(chr(k) for k in range(128) if len(repr(chr(k))) == 3)
>>> print(printable_ascii)
' !"#$%&\'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~'
The last string here, printable_ascii contains only those characters that contain no escapes (i.e. have length == 1). The chars like: \x05, \x06 or \t, \n which does not have its own glyph in your system's font, are filtered out.
len(repr(chr(k))) == 3 includes 2 quotes that come from repr call.
Without doing several appends:
var s = Array.apply(null, Array(127-32))
.map(function(x,i) {
return String.fromCharCode(i+32);
}).join("");
document.write(s);
Here is an ES6 one liner:
asciiChars = Array.from({ length: 95 }, (e, i) => String.fromCharCode(i + 32)).join('');
console.log(asciiChars)
let str = '';// empty string declear
for( var i = 32; i <= 126; i++ )
{
str = str + String.fromCharCode( i ); /* this method received one integer and
convert it into a ascii characters and store it str variable one by one by using
string concatenation method. The loop start for 32 and end 126 */
}
Here is a version in coffeescript
require 'fluentnode'
all_Ascii = ->
(String.fromCharCode(c) for c in [0..255])
describe 'all Ascii', ->
it 'all_Ascii', ->
all_Ascii.assert_Is_Function()
all_Ascii().assert_Size_Is 256
all_Ascii()[0x41].assert_Is 'A'
all_Ascii()[66 ].assert_Is 'B'
all_Ascii()[50 ].assert_Is '2'
all_Ascii()[150 ].assert_Is String.fromCharCode(150)

Categories