简体   繁体   English

单引号,双引号和无引号的Javascript正则表达式

[英]Javascript regex for single, double and no quotes

I have some html attributes that I would like to change based on different buttons being pressed. 我有一些html属性,我想根据所按下的不同按钮进行更改。 For instance, the width attribute will change. 例如, width属性将改变。 Im looking for a regex with Javascript that can replace the value within the attribute for single, double and no quotes. 我正在寻找一个带有Javascript的正则表达式,该正则表达式可以替换属性中单引号,双引号和无引号的值。

width='200' , width="200" , width=200 width='200'width="200"width=200

EDIT 编辑

The reason im not using jQuery for instance to change the values, is because the element im trying to change, is the value inside of a textarea . 我之所以没有使用jQuery来更改值的原因是因为我试图更改的元素是textarea内部的值。

Quick example. 快速示例。

<textarea>
    <iframe width='200' height='200' />
</textarea>

I would like to change the value, of a value. 我想更改一个值。

var regex = /(width=)(['"])?(\d+)(\2)/;
console.log('width="200"'.replace(regex, '$1$2555$4')); // width="555"
console.log("width='200'".replace(regex, '$1$2555$4')); // width='555'
console.log('width=200'.replace(regex, '$1$2555$4')); // width=555
"width='200', width=\"200\", width=200".replace(/(width=)(?:".*?"|'.*?'|\S*)/g, '$1"555"')
// => width="555", width="555", width="555"

But yeah, this is not a job for regexp. 但是,对,这不是regexp的工作。

Try this 尝试这个

[A-Za-z0-9-+]+=['"]{0,1}[^ ^"^']+['"]{0,1}

This matches a string followed by equal to, then 0 or 1 quotes followed by a string followed by 0 or 1 quote. 这匹配一个字符串,后跟等于,然后是0或1个引号,然后是一个字符串,然后是0或1个引号。 its not perfect, it doesn't catch quotes inside the string 它不是完美的,它不能在字符串内捕获引号

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

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