Get indexOf special characters in ActionScript3 - string

In ActionScript3 i wanted to get the text between 2 quotes from some HTML using a input index value where i would simply increase the 2nd quote characters value by 1. This would be very simple however i have now noticed using indexOf does not seem to work correctly with quotes and other special characters.
So my question is if you have some HTML style text like this:
var MyText:String = '<div style="text-align:center;line-height:150%"><a href="http://www.website.com/page.htm">';
How can i correctly get the index of a quote " or other special character?
Currently i try this:
MyText.indexOf('"',1)
but after 0 it always returns the wrong index value.
Also a quick additional question would be is there a better way than using ' ' to store strings with characters like " inside? So if i had other ' characters etc it won't cause problems.
Edit -
This is the function i had created (usage = GetQuote(MyText,0) etc)
// GetQuote Function (Gets the content between quotes at a set index value)
function GetQuote(Input:String, Index:Number):String {
return String(Input.substr(Input.indexOf('"', Index), Input.indexOf('"', Index + 1)));
}
The return for GetQuote(MyText,0) is "text-align yet i need text-align:center;line-height:150% instead.

First off, index of the first quote is 11 and both MyString.indexOf('"') and MyString.indexOf('"',1) return the right value (the latter also works because you don't actually have a quote at the beginning of your string).
When you need to use an single quote inside another one or a double quote inside another one you need to escape the inner one(s) using backslashes. So to catch a single quote you would use it like '\''
There are several ways of stripping a value from a string. You can use the RegExp class or use standard String functions like indexOf, substr etc.
Now what exactly would you like the result to become? Your question is not obvious.
EDIT:
Using the RegExp class is much easier:
var myText:String = '<div style="text-align:center;line-height:150%"><a href="http://www.website.com/page.htm">';
function getQuote(input:String, index:int=0):String {
// I declared the default index as the first one
var matches:Array = [];
// create an array for the matched results
var rx:RegExp = /"(\\"|[^"])*"/g;
// create a RegExp rule to catch all grouped chars
// rule also includes escaped quotes
input.replace(rx,function(a:*) {
// if it's "etc." we want etc. only so...
matches.push(a.substr(1,a.length-2));
});
// above method does not replace anything actually.
// it just cycles in the input value and pushes
// captured values into the matches array.
return (index >= matches.length || index < 0) ? '' : matches[index];
}
trace('Index 0 -->',getQuote(myText))
trace('Index 1 -->',getQuote(myText,1))
trace('Index 2 -->',getQuote(myText,2))
trace('Index -1 -->',getQuote(myText,-1))
Outputs:
Index 0 --> text-align:center;line-height:150%
Index 1 --> http://www.website.com/page.htm
Index 2 -->
Index -1 -->

Related

adding commas and removing space after each class is copied cheerio

i am not understanding how can add commas after each class is copied i did it using for loop but it gives more different output than I want. There are around 9 div class of .name so when each one is copied i want add commas and remove extra space.
here is my code part:
const A = $('.tag-container.field-name').map((i, section) => {
let B = $(section).find('.name')
return B.text()
})
.get(2)
console.log(A)
Use trim and join:
$(css).get().map(el => $(el).text().trim()).join(', ')
There are two things you want to do here.
To remove any whitespace from the left or right-hand sides of a string (eg. from " foo " to "foo"), you can use the String.trim() method.
Regarding the second point, I assume that in adding commas, you want to end up with a string of classnames, separated with commas, like "foo,bar,baz". The .map method you are already using will return an array of something. You can join elements of an array together as a string with the Array.join() method. The join method takes a single argument which specifies the string to use in between each element.
Put those together, and you end up with something like:
const A = $(".tag-container.field-name")
.map((i, section) => {
let B = $(section).find(".name");
return B.text().trim(); // Note use of trim
})
.join(',') // Join all elements of the array with the `,` character
console.log(A);
// Something like `"foo,bar,baz"`

Regex to capture comma separated numbers enclosed in quotes

I have a large set of JavaScript snippets each containing a line like:
function('some string without numbers', '123,71')
and I'm hoping to get a regex together to pull the numbers from the second argument. The second argument can contain an arbitrary number of comma separated numbers (inlcuding zero numbers), so the following are all valid:
''
'2'
'17,888'
'55,1,6000'
...
The regex '(?:\d+|,)*' successfully matches the quoted numbers, but I have no idea how to match each of the numbers. Placing a capture group around the \d+ seems to capture the last number (if there is one present -- it doesn't work if the second argument is just ''), but none of the others.
In your case, you may match and capture the digits inside the single quotes and then split them with a comma:
var s = "function('some string without numbers', '123,71')";
var res = s.match(/'([\d,]+)'/) || ["", ""];
console.log(res[1].split(','));
The /'([\d,]+)'/ regex will match a ', then 1+ digits or commas (placing that value into Group 1) and then a closing '.
If you want to run the regex globally, use
var s = "function('some string without numbers', '123,71')\nfunction('some string without numbers', '13,4,0')";
var rx = /'([\d,]+)'/g;
var res = [], m;
while ((m=rx.exec(s)) !== null) {
res.push(m[1].split(','));
}
console.log(res);
If you have a numbers in a variable x like this:
var x = '55,1,6000';
then use this to have the list of numbers:
var array = x.split(',');
If you can have some whitespace before/after the comma then use:
var array = x.split('\s*,\s*');
or something like that.
Sometimes it is easier to match the thing that you don't want and split on that.

AS3: Get all substrings from a string in a specified array

This is not a duplicate because all the other questions were not in AS3.
Here is my problem: I am trying to find some substrings that are in the "storage" string, that are in another string. I need to do this because my game server is sending the client random messages that contain on of the strings in the "storage" string. The strings sent from the server will always begin with: "AA_".
My code:
private var storage:String = AA_word1:AA_word2:AA_word3:AA_example1:AA_example2";
if(test.indexOf("AA_") >= 0) {
//i dont even know if this is right...
}
}
If there is a better way to do this, please let me know!
Why not just using String.split() :
var storage:String = 'AA_word1:AA_word2:AA_word3:AA_example1:AA_example2';
var a:Array = storage.split('AA_');
// gives : ,word1:,word2:,word3:,example1:,example2
// remove the 1st ","
a.shift();
trace(a); // gives : word1:,word2:,word3:,example1:,example2
Hope that can help.
Regular Expressions are the right tool for this job:
function splitStorage(storage: String){
var re: RegExp = /AA_([\w]+):?/gi;
// Execute the regexp until it
// stops returning results.
var strings = [];
var result: String;
while(result = re.exec(storage)){
strings.push(result[1]);
}
return strings;
}
The important part of this is the regular expression itself: /AA_([\w]+):?/gi
This says find a match starting with AA_, followed by one-or-more alphanumeric characters (which we capture) ([\w]+), optionally followed by a colon.
The match is then made global and case insensitive with /gi.
If you need to capture more than just letters and numbers - like this: "AA_word1 has spaces and [special-characters]:" - then add those characters to the character set inside the capture group.
e.g. ([-,.\[\]\s\w]+) will also match hyphen, comma, full-stop, square brackets, whitespace and alphanumeric characters.
Also you could do it with just one line, with a more advanced regular expression:
var storage:String = 'AA_word1:AA_word2:AA_word3:AA_example1:AA_example2';
const a:Array = storage.match(/(?<=AA_)\w+(?=:|$)/g);
so this means: one or more word char, preceeded by "AA_" and followed by ":" or the end of string. (note that "AA_" and ":" won't be included into the resulting match)

Algorithms for "shortening" strings?

I am looking for elegant ways to "shorten" the (user provided) names of object. More precisely:
my users can enter free text (used as "name" of some object), they can use up to 64 chars (including whitespaces, punctuation marks, ...)
in addition to that "long" name; we also have a "reduced" name (exactly 8 characters); required for some legacy interface
Now I am looking for thoughts on how to generate these "reduced" names, based on the 64-char name.
With "elegant" I am wondering about any useful ideas that "might" allow the user to recognize something with value within the shortened string.
Like, if the name is "Production Test Item A5"; then maybe "PTIA5" might (or might not) tell the user something useful.
Apply a substring method to the long version, trim it, in case there are any whitespace characters at the end, optionally remove any special characters from the very end (such as dashes) and finally add a dot, in case you want to indicate your abbreviation that way.
Just a quick hack to get you started:
String longVersion = "Aswaghtde-5d";
// Get substring 0..8 characters
String shortVersion = longVersion.substring(0, (longVersion.length() < 8 ? longVersion.length() : 8));
// Remove whitespace characters from end of String
shortVersion = shortVersion.trim();
// Remove any non-characters from end of String
shortVersion = shortVersion.replaceAll("[^a-zA-Z0-9\\s]+$", "");
// Add dot to end
shortVersion = shortVersion.substring(0, (shortVersion.length() < 8 ? shortVersion.length() : shortVersion.length() - 1)) + ".";
System.out.println(shortVersion);
I needed to shorten names to function as column names in a database. Ideally, the names should be recognizable for users. I set up a dictionary of patterns for commonly occuring words with corresponding "abbreviations". This was applied ONLY to those names which were over the limit of 30 characters.

C++ Replacing non-alpha/apostrophe with spaces in a string

I am reading in a text file and parsing the words into a map to count numbers of occurrences of each word on each line. I am required to ignore all non-alphabetic chars (punctuation, digits, white space, etc) except for apostrophes. I can figure out how to delete all of these characters using the following code, but that causes incorrect words, like "one-two" comes out as "onetwo", which should be two words, "one" and "two".
Instead, I am trying to now replace all of these values with spaces instead of simply deleting, but can't figure out how to do this. I figured the replace-if algorithm would be a good algorithm to use, but can't figure out the proper syntax to accomplish this. C++11 is fine. Any suggestions?
Sample output would be the following:
"first second" = "first" and "second"
"one-two" = "one" and "two"
"last.First" = "last" and "first"
"you're" = "you're"
"great! A" = "great" and "A"
// What I initially used to delete non-alpha and white space (apostrophe's not working currently, though)
// Read file one line at a time
while (getline(text, line)){
istringstream iss(line);
// Parse line on white space, storing values into tokens map
while (iss >> word){
word.erase(remove_if(word.begin(), word.end(), my_predicate), word.end());
++tokens[word][linenum];
}
++linenum;
}
bool my_predicate(char c){
return c == '\'' || !isalpha(c); // This line's not working properly for apostrophe's yet
}
bool my_predicate(char c){
return c == '\'' || !isalpha(c);
}
Here you're writing that you want to remove the char if it is and apostrophe or if it is not an alphabetical character.
Since you want to replace these, you should use std::replace_if() :
std::replace_if(std::begin(word), std::end(word), my_predicate, ' ');
And you should correct your predicate too :
return !isalpha(c) && c != '\'';
You could use std::replace_if to pre-process the input line before sending it to the istringstream. This will also simplify your inner loop.
while (getline(text, line)){
replace_if(line.begin(), line.end(), my_predicate, ' ');
istringstream iss(line);
// Parse line on white space, storing values into tokens map
while (iss >> word){
++tokens[word][linenum];
}
++linenum;
}

Resources