简体   繁体   中英

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)

and I want regex to delete the first character '(' , the last ')' and replace '||' with ','

so the final output is tags:taga,tagb,tagc

Have tried it but no lucks. I can do this from controller but not right in the html. Any help is greatly appreciated.

-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(',');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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