I have a JSON object property that is a string and looks like this:
"&1 *UBIN 8 &2 *UBIN 8 &3 *UBIN 8 &4 *CHAR 10 &5 *UBIN 8 &6 *UBIN 8 &7 *UBIN 8 &8 *CCHAR *VARY 4"
I want to parse this property (string) to extract the numbers that have an & (ampersand) in front of them, and place each extracted &number into an array. The result would look like:
var array = ['&1', '&2', '&3', '&4', '&5', '&6', '&7', '&8'];
I am using AngularJS.
Any suggestions on how to best accomplish this?
try this
var str="&1 *UBIN 8 &2 *UBIN 8 &3 *UBIN 8 &4 *CHAR 10 &5 *UBIN 8 &6 *UBIN 8 &7 *UBIN 8 &8 *CCHAR *VARY 4";
var result = $.map(str.split(" "), function(element) {
if ( element.substring(0,1) == "&") return element;
});
result
["&1","&2","&3","&4","&5","&6","&7","&8"]
The algorithm for this would be "split() and filter()".
A naive approach could check if the first character is an ampersand:
input = "&1 *UBIN 8 &2 *UBIN 8 &3 *UBIN 8 &4 *CHAR 10 &5 *UBIN 8 &6 *UBIN 8 &7 *UBIN 8 &8 *CCHAR *VARY 4"
input.split(" ").filter(item => item.startsWith("&"))
This works well and is fast, but makes the assumption that only numbers can come after &
, so it will also return items like &abc
.
You could also use a regex:
input.split(" ").filter(item => item.match(/^&\d+$/))
This is slower, but it's more robust. It also makes the assumption that only full-number items are allowed, so it will reject items like &12a
.
Both solutions can be adapted if the full list of requirements differ, as from the question is not fully clear if:
&
are known to contain only numbers, or can contain other characters too
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.