简体   繁体   English

正则表达式替换特殊字符

[英]regex to replace the special characters

I have the following code 我有以下代码

 <span id="{{policy.pname}}_query" class="policy-tag">{{policy.policy_groups[0].query}}</span> 

and the output of 和的输出

 policy.policy_groups[0].query

is tags:(taga || tagb || tagc) tags:(taga || tagb || tagc)

and I want regex to delete the first character '(' , the last ')' and replace '||' 我希望正则表达式删除第一个字符'(',最后一个')'并替换'||' with ',' 与“,”

so the final output is tags:taga,tagb,tagc 所以最终输出是tags:taga,tagb,tagc

Have tried it but no lucks. 尝试过但没有失败。 I can do this from controller but not right in the html. 我可以从控制器执行此操作,但不能在html中执行此操作。 Any help is greatly appreciated. 任何帮助是极大的赞赏。

-kim -kim

Essentially this: 本质上是这样的:

 console.log( 'tags:(taga || tagb || tagc)'.replace(/\\(|\\)/g, "").replace(/\\s*\\|\\|\\s*/g, ",") ) 

Explanation: 说明:

.replace(
  / <-- open regex
  \( <-- find literal opening parenthesis
  | <-- or
  \) <-- find literal closing parenthesis
  /g <-- in the whole string
  ,  <-- "replace" method delimiter
  "" <-- replace with empty string
)
.replace( 
  / <-- open regex again
  \s* <-- find zero or more spaces
  \| <-- find a pipe
  \| <-- find another pipe
  \s* <-- find zero or more spaces after that
  /g <-- in the whole string
  , <-- "replace" method delimiter
  "," <-- replace with commas
)

This regex assumes that there are no parenthesis in your tags, if that is not the case, let me know and I'll update this to address that. 此正则表达式假定您的标记中没有括号,如果不是这种情况,请告诉我,我将对此进行更新。

I hope that helps! 希望对您有所帮助!

假设您可以使用替换过滤器( https://www.npmjs.com/package/angularjs-filters

 <span id="{{policy.pname}}_query" class="policy-tag">{{policy.policy_groups[0].query | string.replace:"/([\\(\\)]| *\\|{2} *)/": "," }}</span> 

You could also do this without regular expressions. 您也可以不使用正则表达式来执行此操作。 More verbose, but easier to read and maintain. 更详细,但更易于阅读和维护。

var string = policy.policy_groups[0].query;
var first = string.indexOf('(');
var last = string.indexOf(')');
string = string.substring(0, first) + string.substring(first + 1, last) + string.substring(last + 1);
string.split(' || ').join(',');

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

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