Im currently loading some text through XML via my doc class - this text contains \n tags
XML example:
What im looking to do is replace \n in my string with
I've tried a few things:
string = string.split("\n").join('<br/>');
and
string = string.replace("\n","<br/>");
However tracing out string afterwards, or just seeing what myTextField.htmlText = string; displays, I still see the \n tags
Any ideas?
Code illustrated:
// The string which contains the XML loaded content
var string:String;
var myTextField:TextField = new TextField();
myTextField.defaultTextFormat = myFormat;
myTextField.width = 300;
myTextField.border = false;
myTextField.embedFonts = true;
myTextField.multiline = true;
myTextField.wordWrap = true;
myTextField.selectable = false;
myTextField.htmlText = string;
addChild(myTextField);
You want:
string = string.replace(/\n/g, "<br>");
This will replace all newlines with <br>.
I believe you want:
str = str.replace("\\n", "\n");
OR the following applies to all instances:
str = str.split("\\n").join("\n");
Try that
The solution above didnt work for me
string = string.replace(/\n/g, "<br>");
I was able to do the same thing this way
string = string.replace(new RegExp(String.fromCharCode(13), "<br>");
im using flash cs6-as3
hopefully this helps if the other doesnt work for you
Related
I have a question regarding to my project which is how to read a string in AS3.
Actually, I have an text file named test.txt. For instance:
It consists of:
Sun,Mon,Tue,Wed,Thu,Fri,Sat
and then I want to put all of them into an array and then a string to show them in the dynamic text Box called text_txt:
var myTextLoader:URLLoader = new URLLoader();
myTextLoader.addEventListener(Event.COMPLETE, onLoaded);
function onLoaded(e:Event):void
{
var days:Array = e.target.data.split(/\n/);
var str:String;
stage.addEventListener(MouseEvent.CLICK, arrayToString);
function arrayToString(e:MouseEvent):void
{
for (var i=0; i<days.length; i++)
{
str = days.join("");
text_txt.text = str + "\n" + ";"; //it does not work here
}
}
}
myTextLoader.load(new URLRequest("test.txt"));
BUT IT DOES NOT show them in different line and then put a ";" at the end of each line !
I can make it to show them in different line, but I need to put them in different line in txt file and also I still do not get the ";" at the end of each line unless put it in the next file also at the end of each line.
And then I want to read the string and show an object from my library based on each word or line. for example:
//I do not know how to write it or do we have a function to read a string and devide it to the words after each space or line
if (str.string="sun"){
show(obj01);
}
if (str.string="mon"){
show(obj02);
}
I hope I can get the answer for this question.
Please inform me if you can not get the concept of the last part. I will try to explain it more until you can help me.
Thanks in advance
you must enable multiline ability for your TextField (if did not)
adobe As3 DOC :
join() Converts the elements in an array to strings, inserts the
specified separator between the elements, concatenates them, and
returns the resulting string. A nested array is always separated by a
comma (,), not by the separator passed to the join() method.
so str = days.join(""); converts the Array to a single string, and as your demand ( parameter passed to join is empty "") there is no any thing between fetched lines. and text_txt.text = str + "\n" + ";"; only put a new line at the end of the text once.
var myTextLoader:URLLoader = new URLLoader();
var days:Array;
myTextLoader.addEventListener(Event.COMPLETE, onLoaded);
function onLoaded(e:Event):void
{
days = e.target.data.split(/\n/);
var str:String;
stage.addEventListener(MouseEvent.CLICK, arrayToString);
}
myTextLoader.load(new URLRequest("test.txt"));
function arrayToString(e:MouseEvent):void
{
text_txt.multiline = true;
text_txt.wordWrap = true;
text_txt.autoSize = TextFieldAutoSize.LEFT;
text_txt.text = days.join("\n");
}
also i moved arrayToString out of onLoaded
for second Question: to checking existance of a word, its better using indexOf("word") instead comparing it with "==" operator, because of invisible characters like "\r" or "\n".
if (str.indexOf("sun") >= 0){
show(obj01);
}
if (str.indexOf("mon") >= 0){
show(obj02);
}
Answer to the first part:
for (var i=0; i<days.length; i++)
{
str = days[i];
text_txt.text += str + ";" + "\n";
}
I hope I understand you correctly..
I wrote from memory, sorry for typos if there are...
For the second part, add a switch-case
switch(str) {
case "sun":
Show(??);
break;
.
.
.
}
I am trying to fetch images tags from a specific div in a web page. Here is the web page link page link
I have used this code:
var webGet = new HtmlWeb();
var document = webGet.Load(txt.Text);
var infos = from info in document.DocumentNode.SelectNodes("//div[#id='custom-description']")
from link in info.SelectNodes("img").Where(x => x.Attributes.Contains("src"))
select new
{
LinkURL = link.Attributes["src"].Value
};
lbl.Text = infos.ToString();
but it returns null value.
Please tell me whats wrong in this code.
Thanks in advance
HtmlWeb web = new HtmlWeb();
HtmlAgilityPack.HtmlDocument document = web.Load(url);
var rateNode = from info in document.DocumentNode.SelectNodes("//div[#class='class name']")
from link in info.SelectNodes("//img").Where(x=>x.Attributes.Contains("src"))
select new
{
link.Attributes["src"].Value
};
// return View(lstRecords);
string result;
lbl.Text = rateNode.ToString();
foreach (var a in rateNode)
{
int count=0;
Image img = new Image();
img.ID = count + "a";
count++;
img.ImageUrl = a.Value
Controls.Add(img);
}
The Linq query you have written here is looking ok. But the problem here is div with id custom-descriptiondoes not contain img element. Hence query returns null result.
Let's say I have a string
var myString: String = "This ***is*** my ***string***"
Now I'm searching for a way to replace the stars with html-bold tags.
After replacement the code should look like:
"This <b>is</b> my <b>string</b>
What I've done so far:
var boldPattern : RegExp = /\*\*\*.*?\*\*\*/;
while(boldPattern.test(goalOv[gCnt][1])){
myString = myString.replace(boldPattern, "<b>"+myString+"</b>");
}
This ends up with an endless Loop (because I'm assigning the string to itself).
Thanks
I'm not good at regular expressions, but I think this simple solution will do the trick:
var boldPattern : RegExp = /(\*\*\*)/;
var myString: String = "This ***is*** my ***string***";
var count:int = 0;
while(boldPattern.test(myString))
{
if(count % 2 == 1)
myString = myString.replace(boldPattern, "</b>");
else
myString = myString.replace(boldPattern, "<b>");
count++;
}
As Gio said, that looping isn't the best way of replacing globally. You should instead do the following to avoid looping and have replacement in one pass over the string.
var boldPattern :String = "This ***is*** my ***string***";
var myString:RegExp = /\*\*\*([^*]*)\*\*\*/g;
var replText:String = "<b>$1</b>";
myString = myString.replace(boldPattern, replText);
Also, if you want to do it more correctly to allow for myString have have string of 1 or 2 *, you can use:
/\*\*\*(([^*]+\*{0,2})+)\*\*\*/g
I want to implement an alogorithm/validation. How can I find out if a string contains a specific character more than 6 times in Flex ?
There are 2 ways, I can think of:
Use RegExp and .replace() like this:
var ch:String = "a"; //Character, that must be checked
var text:String = "This is an example to show how many times '"+ch+"' occured.";
//Matches non-`ch` characters
var regexp:RegExp = new RegExp("[^"+ch+"]","g");
//Replacing non-`ch` characters with empty string
var timesOccured:Number = text.replace(regexp,"").length;
trace(text, ": " ,timesOccured );
Use RegExp and .match() like this:
var ch:String = "a"; //Character, that must be checked
var text:String = "This is an example to show how many times '"+ch+"' occured.";
//Matches `ch` characters
var regexp:RegExp = new RegExp(ch,"g");
var matches:Array = text.match(regexp);
var timesOccured:Number = 0;
//`matches` can be 'null', so we are performing additional check
if( matches ){
timesOccured = matches.length;
}
trace(text, ": " ,timesOccured );
Now when you have timesOccured, you could easily do your validation:
if( timesOccured > 6 ){
//Do some stuff
}else{
//Do other stuff
}
Warning: If your ch is a special character for Regular Expression, like a .,+,(,],\,etc..., you need to escape it, before passing it to regexp variable:
ch = ch.replace(new RegExp("[.*+?|()\\[\\]{}\\\\]", "g"), "\\$&");
a simpler alternative to regular expressions can be the following:
var str:String = "This is an example to show how many...";
//find occurrences for character 'a'
trace("Ocurrences:" + str.split('a').length-1);
I'm trying to load a txt file of variables into my AS3 project. The problem I have though seems to be down to the fact that the txt file (which is pre formatted and cannot be changed) is formatted using double amphersands... e.g.
&name=mark&
&address=here&
&tel=12345&
I'm using the following code to load the txt file
myLoader.addEventListener(Event.COMPLETE, onLoaded, false, 0, true);
myLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
urlRqSend = new URLRequest(addressToTxt.txt);
public function onLoaded(e:Event):void {
trace(myLoader.data);
}
Using URLLoaderDataFormat.VARIABLES generates the following error:
Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
If I use URLLoaderDataFormat.TEXT I can load the data successfully but I'm not able (or don't know how to) access the variables.
Would anyone have any ideas or work arounds to this please.
Thanks,
Mark
I had that kind of problem some time ago.
I suggest you to load first as a text, remove those line breaks, the extra amphersands and parse manually:
var textVariables:String;
var objectVariables:Object = new Object();
...
myLoader.addEventListener(Event.COMPLETE, onLoaded, false, 0, true);
myLoader.dataFormat = URLLoaderDataFormat.TEXT;
urlRqSend = new URLRequest(addressToTxt.txt);
public function onLoaded(e:Event):void {
textVariables = myLoader.data;
textVariables = textVariables.split("\n").join("").split("\r").join(""); // removing line breaks
textVariables = textVariables.split("&&").join("&"); // removing extra amphersands
var params:Array = textVariables.split('&');
for(var i:int=0, index=-1; i < params.length; i++)
{
var keyValuePair:String = params[i];
if((index = keyValuePair.indexOf("=")) > 0)
{
var key:String = keyValuePair.substring(0,index);
var value:String = keyValuePair.substring(index+1);
objectVariables[key] = value;
trace("[", key ,"] = ", value);
}
}
}
I wrote that code directly here, I don't have any AS3 editor here, so, maybe you'll find errors.
If you have data in String and it has a structure just like you wrote, you can do a workaround:
dataInString = dataInString.split("\n").join("").split("\r").join(""); // removing EOL
dataInString = dataInString.slice(0,-1); // removing last "&"
dataInString = dataInString.slice(0,1); // removing first "&"
var array:Array = dataInString.split("&&");
var myVariables:Object = new Object();
for each(var item:String in array) {
var pair:Array = item.split("=");
myVariables[pair[0]] = pair[1];
}
That should make you an object with proper variables.