Hello, I'm a beginner looking to better understand how script labels can be parsed.
I have applied a script label to a frame that has both letters and numbers. I am attempting to extract both using the string.match() method and the parseInt() function
My results are changing depending on where the number is in the script label. Why is this? How can i get both the string and the int from my label?
//Label = 1elephant var frameLabel = app.activeDocument.selection.label alert(frameLabel); // 1elephant alert(parseInt(frameLabel)); // 1 alert(frameLabel.match(/[A-za-z]*/)); // alerts nothing / empty string //Label = elephant1 var frameLabel = app.activeDocument.selection.label alert(frameLabel); // elephant1 alert(parseInt(frameLabel)); // NaN alert(frameLabel.match(/[A-za-z]*/)); // elephant
Match returns an array, so you need to get all instances of the match (if there's just one, assume it's ).
\d is wildcard for digit
You also want a capital Z for your string search
* matches 0 or more, so depending on how the string is configured, it was returning nothing. Use + instead, which matches 1 or more instances
Thansks, this makes sense.
I see none of these responses are using parseInt(). should I avoid it?
Do you know why it returns NaN when I have an integer as the last digit of my string?
You can use parseInt where your string already looks like a number. It failed to coerce "elephant1" to an integer because, according to this documentation, it returns NaN if the first non-whitespace character cannot be converted to a number. In your use case, all the other options on this thread are probably better unless your script label is a string that looks like a normal number. Note that parseInt should always be used with the radix argument, eg. parseInt("123", 10)—again see documentation.
Just for learning, here's another approach that might suit your needs.
1. Delimit the string from the number using, for example, a pipe character ( | ) or comma etc.
2. Split the label at the delimiter character
3. Parse the results more easily.
// assume label is "elephant|1" var frameLabel = app.activeDocument.selection.label; var frameFields = frameLabel.split('|'); var myString = frameFields; var myNumber = Number(frameFields);
to get the string without the numbers:
var label = "12345Some text 123 text 2 text 2"; var alphaStrings = label.split(/\d+/).join(""); alert( alphaStrings );
( ACP )
var label = "12345Some text 123 text 2 text 2"; var numbersOnly = label.split(/\D+/).join(""); alert( numbersOnly ); // 1234512322
Warning: all numbers will be concatenated to one single number in case there are more numbers than one.
( ACP )