我有一个以这种格式的变量对象值:
"Landing Hits: 0Rewards Hits: 0Facebook Posts: 0Twitter Tweets: 0Twitter Autofollows: 0Instagram Photos: 0Instagram Likes: 0Instagram Votes: 0Pinterest Pins: 0Form Submissions: 0Submissions: 0Engagement: 0Views: 0Prints: 0"
我需要将其转换为:
"Landing Hits: 0, Rewards Hits: 0, Facebook Posts: 0, Twitter Tweets: 0, Twitter Autofollows: 0, Instagram Photos: 0, Instagram Likes: 0, Instagram Votes: 0, Pinterest Pins: 0, Form Submissions: 0, Submissions: 0, Engagement: 0, Views: 0, Prints: 0"
任何想法如何做到这一点?
答案 0 :(得分:4)
您可以使用RegEx搜索匹配项。
rdd1.flatMap(flattenLine)

只需替换:如果您只需更换字符串,您也可以这样做:
var str = "Landing Hits: 0Rewards Hits: 0Facebook Posts: 0Twitter Tweets: 0Twitter Autofollows: 0Instagram Photos: 0Instagram Likes: 0Instagram Votes: 0Pinterest Pins: 0Form Submissions: 0Submissions: 0Engagement: 0Views: 0Prints: 0";
var arr = str.match(/[^:]+\s*:\s*\d+/g); //Find values like `String:Number`
var out = arr.join(", "); //Convert array matches to String
document.write("<pre>" + out + "</pre>"); //Test
&#13;
扩展为对象:这允许您处理为其他目的而获得的值
var str = "Landing Hits: 0Rewards Hits: 0Facebook Posts: 0Twitter Tweets: 0Twitter Autofollows: 0Instagram Photos: 0Instagram Likes: 0Instagram Votes: 0Pinterest Pins: 0Form Submissions: 0Submissions: 0Engagement: 0Views: 0Prints: 0";
var formatted = str.replace(/(\d)(\w)/g, "$1, $2");
document.write(formatted)
&#13;
答案 1 :(得分:0)
你可以试试这个:
var c = "Landing Hits: 0345Rewards Hits: 0Facebook Posts: 0Twitter Tweets: 034534532Twitter Autofollows: 0Instagram Photos: 0Instagram Likes: 0Instagram Votes: 0Pinterest Pins: 0Form Submissions: 0Submissions: 0Engagement: 0Views: 0Prints: 0";
var array = []
var counter = 0;
var num;
var dup = "";
for (var i = 0; i < c.length; i++) {
dup += c[i];
if (c[i]==":"){dup+=" ";}
if (!isNaN(c[i]) && isNaN(c[i+1]) && c[i]!=" ") {
dup += ", "
}
}
alert(dup);
答案 2 :(得分:0)
在代码中添加以下行
var str = "Landing Hits: 0Rewards Hits: 0Facebook Posts: 0Twitter Tweets: 0Twitter Autofollows: 0Instagram Photos: 0Instagram Likes: 0Instagram Votes: 0Pinterest Pins: 0Form Submissions: 0Submissions: 0Engagement: 0Views: 0Prints: 0";
alert(str.replace(/0|_/g,'0,'));
答案 3 :(得分:0)
您不需要Regex
:
var str = "Landing Hits: 0Rewards Hits: 0Facebook Posts: 0Twitter Tweets: 0Twitter Autofollows: 0Instagram Photos: 0Instagram Likes: 0Instagram Votes: 0Pinterest Pins: 0Form Submissions: 0Submissions: 0Engagement: 0Views: 0Prints: 0";
var newStr = str.split(0).join('0, ').slice(0, -2);