jQuery:从attr替换字符串中的\ u002D?

时间:2015-03-26 20:00:22

标签: jquery replace

从这个div我想提取“ng-init”

中的URL
<div ng-controller="CloudcastHeaderCtrl" ng-init="juno.replaceTracklist=true;juno.guid='DBFFF66E\u002D4111\u002D446B\u002D8471\u002D07DF1489F272';juno.chartUrl='http://www.junodownload.com/charts/mixcloud/RYCpodcast/ryc\u002Dpodcast\u002D108\u002Dpearl/254201612'">

但我似乎无法用\u002D

替换-

var ngInit = $('div[ng-controller="CloudcastHeaderCtrl"]').attr("ng-init"),
    url = ngInit.replace(/.+juno\.chartUrl='(.+)'/, "$1"),
    urlR = url.replace("\u002D", "-");

$("body").append( url + "<br />" );
$("body").append( urlR );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div ng-controller="CloudcastHeaderCtrl" ng-init="juno.replaceTracklist=true;juno.guid='DBFFF66E\u002D4111\u002D446B\u002D8471\u002D07DF1489F272';juno.chartUrl='http://www.junodownload.com/charts/mixcloud/RYCpodcast/ryc\u002Dpodcast\u002D108\u002Dpearl/254201612'">

测试:http://jsfiddle.net/7o7kL5pp/

1 个答案:

答案 0 :(得分:1)

反斜杠是一个逃避角色。由于目标字符串包含文字反斜杠,因此您需要将其转义。

var ngInit = $('div[ng-controller="CloudcastHeaderCtrl"]').attr("ng-init"),
    url = ngInit.replace(/.+juno\.chartUrl='(.+)'/, "$1"),
    urlR = url.replace("\\u002D", "-");

$("body").append( url + "<br />" );
$("body").append( urlR );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div ng-controller="CloudcastHeaderCtrl" ng-init="juno.replaceTracklist=true;juno.guid='DBFFF66E\u002D4111\u002D446B\u002D8471\u002D07DF1489F272';juno.chartUrl='http://www.junodownload.com/charts/mixcloud/RYCpodcast/ryc\u002Dpodcast\u002D108\u002Dpearl/254201612'">