简体   繁体   中英

javascript regexp backreferences in character class possible?

Does javascript regular expressions support backreferences inside character class?

I want to do something like this:

htmlString.replace(/attribute_name=(['"])[^\1]*\1/,'')

But that does not work. This does:

htmlString.replace(/attribute_name=(['"])[^'"]*\1/,'')

Unfortunatelly my attribute_name can contain apostrophes or quotes, so I need to exlude the actual quoting character from the inside of the attribute, but leave the other one. I can't be sure which one is used. I can safely assume that quotes are in form of entity, but still there can be apostrophes inside:

<div attribute_name="John's car" class="someClass"></div>
<div attribute_name='some &quot;quoted text&quot;' class="someClass"></div>

I am not able to predict which of " or ' will be used around the attribute.

How to get rid of the attribute and leave the class attribute alone (not cut too much)?

context: I am getting the html by $('templateContainer').innerHTML . I have to modify that html before inserting it into the page again. I have to cut some non-standard attibutes and all the ID attributes.

I agree with the other answers in that I don't think that the attributes are the place to do this type of thing, but I'm also wary of recommending the DOM either. I just feel dirty when I do that, I don't know why.

I usually will try to use a javascript object to store my data in and then reference it using well-formed keys, etc. shrug It's more work, but it's cleaner IMHO. But, it definitely isn't the only way to accomplish the task.

As to your question, you could also use the non-greedy matching in JavaScript and it would look like this:

htmlString.replace(/ ?attribute_name=(['"]).*?\1/, '')

Regular Expressions in JavaScript | evolt.org

You'd be a LOT better off using DOM or some other actual model designed for hierarchical content. That said, if you must use regex, the simplest way would probably be to just use a | (OR) instead.

htmlString.replace(/attribute_name=('[^']*'|"[^"]*")/,'')

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