[英]Extracting value from string using regex and Javascript
Given a string like: 给定一个像这样的字符串:
</gd:organization><gd:email rel='http://schemas.google.com/g/2005#other' address='CM@Aart.com'/><gd:email rel='http://schemas.google.com/g/2005#other' address='da@ammeart.com' primary='true'/><gd:phoneNumber rel='http://schemas.google.com/g/2005#work'>011 360 51 60</gd:phoneNumber>
I need to remove from the string: 我需要从字符串中删除:
<gd:email rel='http://schemas.google.com/g/2005#other' address='CM@Aart.com'/>
- based on a match to: CM@Aart.com
. -基于与CM@Aart.com
的匹配。
It has to be done in basic JavaScript and I can't import any special parsing tools. 它必须使用基本的JavaScript来完成,我无法导入任何特殊的解析工具。 I can't seem to find a combination that does not error out. 我似乎找不到一个不会出错的组合。
Thank you! 谢谢!
This is simple enough, do tell if you need any changes: 这很简单,请确定是否需要任何更改:
var inputString = "</gd:organization><gd:email rel='http://schemas.google.com/g/2005#other' address='CM@Aart.com'/><gd:email rel='http://schemas.google.com/g/2005#other' address='da@ammeart.com' primary='true'/><gd:phoneNumber rel='http://schemas.google.com/g/2005#work'>011 360 51 60</gd:phoneNumber>";
var outputString = inputString.split("CM@Aart.com")[1].substring(3);
alert(outputString);
If this must be done in RegExp, you could attempt something like the following only if you know that all <gd:email>
parts will have an address attribute, quotes are '
and end />
without address='
or />
appearing inside any values on those attributes. 如果必须在RegExp中完成此操作,则仅当您知道所有<gd:email>
部分都将具有address属性,且引号是'
并且结尾/>
而没有address='
或/>
出现在任何内容中时, 才可以尝试以下操作这些属性上的值。
"</gd:organization><gd:email rel='http://schemas.google.com/g/2005#other' address='CM@Aart.com'/><gd:email rel='http://schemas.google.com/g/2005#other' address='da@ammeart.com' primary='true'/><gd:phoneNumber rel='http://schemas.google.com/g/2005#work'>011 360 51 60</gd:phoneNumber>"
.replace(
/<gd:email .*?address='([^']*)'.*?\/>/g, // match email node
function (a, b) { // replacement logic
if (b === 'CM@Aart.com') return '';
return a;
}
);
As I said in my comment , the best way to achieve this would actually be with DOMParser
which is a native JavaScript XML parser, but the string you have given us is not valid XML as it begins with a close tag. 正如我在评论中所说,实现此目标的最佳方法实际上是使用DOMParser
,它是一个本机JavaScript XML解析器,但是您给我们提供的字符串不是有效的XML,因为它以close标记开头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.