在javascript中获取字符串的一部分

时间:2016-09-28 14:41:30

标签: javascript string

如何从字符串中获取坐标:

<path fill="#FFFFFF" stroke="#000000" stroke-miterlimit="10" d="M275.843,110.301c-47.082,13.406-77.458,58.874-69.425,103.478
        c4.241,23.548,16.136,42.268,38.639,52.408c4.728,2.13,10.717,1.457,16.125,2.08c25.394,2.925,46.609,15.095,66.295,30.378
        c3.857,2.995,6.64,2.91,10.014-0.096c24.818-22.111,39.262-49.192,39.892-84.204c-0.189-2.728-0.244-6.743-0.775-10.694
        c-5.566-41.427-27.104-72.584-61.608-95.299c-1.563-1.029-3.687-1.618-5.573-1.682
        C298.075,106.287,286.912,107.148,275.843,110.301z"></path>

我需要d=""之后的所有坐标,所以我只需要数字:

M275.843,110.301c-47.082,13.406-77.458,58.874-69.425,103.478
            c4.241,23.548,16.136,42.268,38.639,52.408c4.728,2.13,10.717,1.457,16.125,2.08c25.394,2.925,46.609,15.095,66.295,30.378
            c3.857,2.995,6.64,2.91,10.014-0.096c24.818-22.111,39.262-49.192,39.892-84.204c-0.189-2.728-0.244-6.743-0.775-10.694
            c-5.566-41.427-27.104-72.584-61.608-95.299c-1.563-1.029-3.687-1.618-5.573-1.682
            C298.075,106.287,286.912,107.148,275.843,110.301z

或者我怎样才能获得d的这个值。 Becouse目标返回给我所有信息,但当我写

target.d

没有发生任何事情

3 个答案:

答案 0 :(得分:0)

在vanilla javascript中:

document.getElementById('elementId').getAttribute('d');

使用jquery使用.attr():

$('#elementId').attr('d');

答案 1 :(得分:0)

使用Regexp:

var myString = '<path fill="#FFFFFF" stroke="#000000" stroke-miterlimit="10" d="M275.843,110.301c-47.082,13.406-77.458,58.874-69.425,103.478c4.241,23.548,16.136,42.268,38.639,52.408c4.728,2.13,10.717,1.457,16.125,2.08c25.394,2.925,46.609,15.095,66.295,30.378c3.857,2.995,6.64,2.91,10.014-0.096c24.818-22.111,39.262-49.192,39.892-84.204c-0.189-2.728-0.244-6.743-0.775-10.694c-5.566-41.427-27.104-72.584-61.608-95.299c-1.563-1.029-3.687-1.618-5.573-1.682C298.075,106.287,286.912,107.148,275.843,110.301z"></path>';

var myRegexp = /d=\"(.*|\s)\">/g;

var match = myRegexp.exec(myString);

然后你想要的是:

match[1]

答案 2 :(得分:0)

使用getAttribute()方法:

event.target.getAttribute('d')