Find word that starts at a newline - actionscript-3

I have a simple loop to delete all words from the end of a text that start with a # and space.
AS3:
// messageText is usually taken from a users input field - therefore the newline is not present in the "messageText"
var messageText = "hello world #foo lorem ipsum #findme"
while (messageText.lastIndexOf(" ") == messageText.lastIndexOf(" #")){
messageText = messageText.slice(0,messageText.lastIndexOf(" "));
}
How to check if the position before the # is not a space but a newline?
I tried this but nothing gets found:
while (messageText.lastIndexOf(" ") == messageText.lastIndexOf("\n#")){
messageText = messageText.slice(0,messageText.lastIndexOf(" "));
}

\n is the newline character in the Unix file definition.
\r\n is the Windows version.
\r is the OSX version.
See also: this previous (dupe) post.
First thing is I'd manually try replacing "\n" with "\r\n" and then "\r" to see if there is some other newline in use. If so, then you just need a better search term that will match each version in one go.
A better solution might be to use Regular Expression (RegExp). You are explicitly looking for the newline character and a space after it. You could use this regex pattern to look for the start of a line with a single space:
var pattern:RegExp = /^\s/;
if (yourString.search(pattern) >= 0) { ... }
The ^ carat character enforces that it's the start of a line. The \s is a placeholder for any whitespace character, so if you don't want to match tabs then change it to a blank space. (I'm not familiar with ActionScript specifically, but that syntax looks OK and search() will return -1 if the pattern isn't found).

Related

Find the word and replace with html tag using regex

I have a text equation like: 10x^2-8y^2-7k^4=0.
How can I find the ^ and replace it with <sup>2</sup> in the whole string using regex. The result should be like:
I tried str = str.replace(/\^\s/g, "<sup>$1</sup> ") but I’m not getting the expected result.
Any ideas that can help to solve my problem?
I think you're looking for something like
\^(\d+)
It matches the ^, captures the exponent and replace with
<sup>$1</sup>
See it here at regex101.
Edit:
To meet your new demands, check this fiddle. It handles the sub as well using replace with a function.
Your current pattern matches a caret followed by a space character (space, tab, new-line, etc.), but you want to match a caret followed by a single character or multiple characters wrapped in accolades, as your string is in TeX.
/\^(?:([\w\d])|\{([\w\d]{2,})\})/g
Now, using str = str.replace(/\^(?:([\w\d])|\{([\w\d]{2,})\})/g, "<sup>$1</sup>"); should do the job.
You can make a more generic function from this expression that can wrap characters prefixed by a specific character with a specific tag.
function wrapPrefixed(string, prefix, tagName) {
return string.replace(new RegExp("\\" + prefix + "(?:([\\w\\d])|\\{([\\w\\d]{2,})\\})"), "<" + tagname + ">$1</" + tagname + ">");
}
For instance, calling wrapPrefixed("1_2 + 4_{3+2}", "_", "sub"); results in 1<sub>2</sub> + 4<sub>3+2</sub>.

Exclude some characters from a Lex regex

I am trying to build a regex for lex that match the bold text in mardown syntax. For example: __strong text__ I thought this:
__[A-Za-z0-9_ ]+__
And then replace the text by
<strong>Matched text</strong>
But in Lex, this rule causes the variable yytext to be __Matched Text__. How could I get rid of the underscores? It would be better to create a regex that does not match the underscores or proccess the variable yytext to remove it?
With capturing groups it would be easer, because I would only need the regex:
__([A-z0-9 ]+)__
And use \1. But Lex does not support capturing groups.
Answer
I finally take the first option offer by João Neto, but a little modified:
yytext[strlen(yytext)-len]='\0'; // exclude last len characters
yytext+=len; // exclude first len characters
I've tried with Start conditions as he mentioned as second option, but did not work.
You can process yytext by removing the first and last two characters.
yytext[strlen(yytext)-2]='\0'; // exclude last two characters
yylval.str = &yytext[2]; // exclude first two characters
Another option is to use stack
%option stack
%x bold
%%
"__" { yy_push_state(bold); yylval.str = new std::string(); }
<bold>"__" { yy_pop_state(); return BOLD_TOKEN; }
<bold>.|\n { yylval.str += yytext; }

Convert QString to text with substitutes for HTML special characters (e.g. tags)

The user will be able to put in some text into a QLineEdit in a Qt environment. However, these input texts can contain HTML special characters. My aim is to convert this text by replacing all HTML special character occurences with substitutes.
A similar case is found in PHP with the htmlspecialchars() function http://php.net/manual/en/function.htmlspecialchars.php.
The main reason I want to do this is because I want to display the user input in a richtext QTextEdit and I don't want the user to be able to change HTML and I wish to be able to use HTML special characters without too much hassle.
How can this be achieved?
The easiest way I know, is to use QTextEdit::toHtml:
QString convert();
{
QString s = lineEdit->text();
QTextEdit textEdit;
textEdit.setPlainText(s);
QString ret = textEdit.toHtml();
int firstClosingTag = ret.indexOf("</p></body></html>");
int lastOpeningTag = ret.lastIndexOf(">", firstClosingTag);
return ret.mid(lastOpeningTag + 1, firstClosingTag - lastOpeningTag - 1);
}
There are also two functions, which you could find useful:
Qt::convertFromPlainText() and Qt::escape()
In Qt5, it's QString::toHtmlEscaped, e.g.:
QString a = "Hello, <span class=\"name\">Bear</span>!";
// a will contain: Hello, <span class="name">Bear</span>!
QString b = a.toHtmlEscaped();
// b will contain: Hello, <span class="name">Bear</span>!
This is direct equivalent of the htmlspecialchars in PHP. It replaces the Qt::escape function (mentioned by Amartel), which does the same thing but is now obsolete.
The Qt::convertFromPlainText function (also mentioned by Amartel) still exists in Qt 5, but it does more than PHP's htmlspecialchars. Not only it replaces < with <, > with >, & with &, " with " but also does additional handling of whitespace characters (space, tab, line feed, etc) to make the generated HTML look visually similarly to the original plain text. Particularly, it may put <p>…</p>/<br> for linefeeds, non-breaking spaces for spaces and multiple non-breaking spaces for tabs. I.e. this function is not just htmlspecialchars, it's even more comprehensive than nl2br(htmlspecialchars($s)) combination.
Note that unlike the PHP's htmlspecialchars with ENT_QUOTES, none of the Qt functions listed in this answer replace single quote (') with &apos;/'. So, for example, QString html = "<img alt='" + s.toHtmlEscaped() + "'>"; won't be safe, only QString html = "<img alt=\"" + s.toHtmlEscaped() + "\">"; will. (However, as < is replaced and ' has no special meaning outside <…>, something like QString html = "<b>" + s.toHtmlEscaped() + "</b>"; would also be safe.)

How to remove more than one whitespace character from HTML?

I want to remove extra whitespace which is coming from the user end, but I can't predict the format of the HTML.
For example:
<p> It's interesting that you would try cfsetting, since nothing in it's
documentation would indicate that it would do what you are asking.
Unless of course you were mis-reading what "enableCFoutputOnly" is
supposed to do.
</p>
<p>
It's interesting that you would try cfsetting, since nothing in it's
documentation would indicate that it would do what you are asking.
Unless of course you were mis-reading what "enableCFoutputOnly" is
supposed to do.</p>
Please guide me on how to remove more than one whitespace character from HTML.
You could use regex to replace any cases of multiple whitespace characters with a single space by looping over the result until no more multiple whitespace occurances exist:
lastTry = "<p> lots of space </p>";
nextTry = rereplace(lastTry,"\s\s", " ", "all");
while(nextTry != lastTry) {
lastTry = nextTry;
nextTry = REReplace(lastTry,"\s\s", " ", "all");
}
Tested working in CF10.
if you don't want to do it thru code out of total lazyness
=> http://jsbeautifier.org/
if you want to do it by code then a regex would be another option
This should do it:
<cfscript>
string function stripCRLFAndMultipleSpaces(required string theString) {
local.result = trim(rereplace(trim(arguments.theString), "([#Chr(09)#-#Chr(30)#])", " ", "all"));
local.result = trim(rereplace(local.result, "\s{2,}", " ", "all"));
return local.result;
}
</cfscript>

How to add a new line in textarea element?

I want to add a newline in a textarea. I tried with \n and <br/> tag but are not working. You can see above the HTML code. Can you help me to insert a newline in a textarea?
<textarea cols='60' rows='8'>This is my statement one.\n This is my statement2</textarea>
<textarea cols='60' rows='8'>This is my statement one.<br/> This is my statement2</textarea>
Try this one:
<textarea cols='60' rows='8'>This is my statement one.
This is my statement2</textarea>
Line Feed and 
 Carriage Return are HTML entitieswikipedia. This way you are actually parsing the new line ("\n") rather than displaying it as text.
Break enter Keyword line in Textarea using CSS:
white-space: pre-wrap;
I think you are confusing the syntax of different languages.
is (the HtmlEncoded value of ASCII 10 or) the linefeed character literal in a HTML string. But the line feed character does NOT render as a line break in HTML (see notes at bottom).
\n is the linefeed character literal (ASCII 10) in a Javascript string.
<br/> is a line break in HTML. Many other elements, eg <p>, <div>, etc also render line breaks unless overridden with some styles.
Hopefully the following illustration will make it clearer:
T.innerText = "Position of LF: " + t.value.indexOf("\n");
p1.innerHTML = t.value;
p2.innerHTML = t.value.replace("\n", "<br/>");
p3.innerText = t.value.replace("\n", "<br/>");
<textarea id="t">Line 1
Line 2</textarea>
<p id='T'></p>
<p id='p1'></p>
<p id='p2'></p>
<p id='p3'></p>
A few points to note about Html:
The innerHTML value of the TEXTAREA element does not render Html. Try the following: <textarea>A <a href='x'>link</a>.</textarea> to see.
The P element renders all contiguous white spaces (including new lines) as one space.
The LF character does not render to a new line or line break in HTML.
The TEXTAREA renders LF as a new line inside the text area box.
I've found String.fromCharCode(13, 10) helpful when using view engines.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode
This creates a string with the actual newline characters in it and so forces the view engine to output a newline rather than an escaped version. Eg: Using NodeJS EJS view engine - This is a simple example in which any \n should be replaced:
viewHelper.js
exports.replaceNewline = function(input) {
var newline = String.fromCharCode(13, 10);
return input.replaceAll('\\n', newline);
}
EJS
<textarea><%- viewHelper.replaceNewline("Blah\nblah\nblah") %></textarea>
Renders
<textarea>Blah
blah
blah</textarea>
replaceAll:
String.prototype.replaceAll = function (find, replace) {
var result = this;
do {
var split = result.split(find);
result = split.join(replace);
} while (split.length > 1);
return result;
};
<textarea cols='60' rows='8'>This is my statement one.
This is my statement2</textarea>
Fiddle showing that it works: http://jsfiddle.net/trott/5vu28/.
If you really want this to be on a single line in the source file, you could insert the HTML character references for a line feed and a carriage return as shown in the answer from #Bakudan:
<textarea cols='60' rows='8'>This is my statement one.
This is my statement2</textarea>
Try this. It works:
<textarea id="test" cols='60' rows='8'>This is my statement one.
This is my statement2</textarea>
Replacing for <br> tags:
$("textarea#test").val(replace($("textarea#test").val(), "<br>", "
")));
To get a new line inside text-area, put an actual line-break there:
<textarea cols='60' rows='8'>This is my statement one.
This is my statement2</textarea>
You might want to use \n instead of /n.
After lots of tests, following code works for me in Typescreipt
export function ReplaceNewline(input: string) {
var newline = String.fromCharCode(13, 10);
return ReplaceAll(input, "<br>", newline.toString());
}
export function ReplaceAll(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
}
You should also check the css white-space property (mdn docs) of your element, make sure it's set to a value that doesn't suppress line breaks, e.g.:
white-space: pre-line;
You'd be interested in these 3 values:
pre
Sequences of white space are preserved. Lines are only broken at
newline characters in the source and at <br> elements.
pre-wrap
Sequences of white space are preserved. Lines are broken at
newline characters, at <br>, and as necessary to fill line boxes.
pre-line Sequences of white space are collapsed. Lines are broken at
newline characters, at <br>, and as necessary to fill line boxes.
My .replace()function using the patterns described on the other answers did not work. The pattern that worked for my case was:
var str = "Test\n\n\Test\n\Test";
str.replace(/\r\n|\r|\n/g,'
');
// str: "Test
Test
Test"
T.innerText = "Position of LF: " + t.value.indexOf("\n");
p3.innerText = t.value.replace("\n", "");
<textarea id="t">Line 1
Line 2</textarea>
<p id='p3'></p>
If you are using react
Inside the function
const handleChange=(e)=>{
const name = e.target.name;
let value = e.target.value;
value = value.split('\n').map(str => <span>{str}<br/></span>);
SetFileds({ ...fileds, [name]: value });
}
A simple and natural solution not involving CSS styles or numeric character references like
would be to use the &NewLine; character entity reference:
The cardinal directions are:&NewLine;- North&NewLine;- East&NewLine;- South&NewLine;- West
Note: Since this is defined simply as the LF (line feed, or the U+000A Unicode code point) character, it's not 100% certain whether it suits situations where the entire CR + LF (carriage return + line feed) sequence is required. But then, it worked in my Chrome, Edge and WebView2 tests done on Windows 10, so it should be ok to use.
just use <br>
ex:
<textarea>
blablablabla <br> kakakakakak <br> fafafafafaf
</textarea>
result:
blablablabla kakakakakak fafafafafaf