简体   繁体   English

网址解析javascript

[英]url parsing javascript

<a href="?action=add&question=149&cat=88">Answer</a>'

this is the url i needed to get href value i cannot use element.getAttribute. 这是我获取href值所需的网址,我无法使用element.getAttribute。 I cannot use dom parsing. 我无法使用dom解析。 But if i try to parse it using search mechanism 但是如果我尝试使用搜索机制来解析它

td3_element = <td valign="top">
<a href="?action=add&question=149&cat=88">Answer</a>
</td>

href_start = td3_element.search("<a href=") + 8;
td3_part   = td3_element.substring(href_start);
href_end   = td3_part.search(">Answer</a>");
href_element = td3_part.substring(0,href_end);

href_element will only be till `?action=addamp`  

it is taking the 它正在

;

character coming after amp as end of line and it is terminating search to that point. 字符在amp之后作为行尾,并且终止搜索到该点。 Can some one tell me a solution which will give the desired href without using DOM parser 有人可以告诉我一种不使用DOM解析器就能给出所需href的解决方案吗

Have you tried a regular expression? 您是否尝试过正则表达式? I'm not sure what you mean just by 'search mechanism'. 我不确定仅通过“搜索机制”意味着什么。

For example: 例如:

var htmlString = 'td3...(etc)';
var regex = /href="([^"])"/;
var hrefUrl = regex.exec()[1];
console.log(hrefUrl); //?action=add&question=149&cat=88 

See also this jsfiddle 另请参阅此jsfiddle

Try a regex 尝试一个正则表达式

var a='<a href="?action=add&question=149&cat=88">Answer</a>';
a.match(/href="(.*)"/)[1];

How about this: 这个怎么样:

JSBIN Demo JSBIN演示

Creating a temp div, setting the innerHtml and parsing, 创建一个temp div,设置innerHtml并进行解析,

var str = '<a href="?action=add&question=149&cat=88">Answer</a>';

var div = document.createElement('div');
div.innerHTML = str;

document.write(div.childNodes[0].getAttribute('href'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM