简体   繁体   English

在两个字符之间替换

[英]Replace between two characters

I want to remove a string that is between two characters, let's say for example I want to replace all characters of the string between "value=" and " " with "" so value will always equal "";我想删除两个字符之间的字符串,例如我想用""替换"value="" "之间字符串的所有字符,因此值将始终等于“”;

Example:例子:

"<input value=98 name=anything>"

To this对此

"<input value= name=anything>"

How could I do it in JavaScript?我怎么能在 JavaScript 中做到这一点?

You could probably use regular expressions here, if the structure of the HTML is always like this.如果 HTML 的结构总是这样,您可能可以在这里使用正则表达式。

But it would get more complicated if you had to consider value=foo , value="foo" or value="foo bar" too.但是,如果您还必须考虑value=foovalue="foo"value="foo bar" ,情况会变得更加复杂。

Here is a more exciting way, which would work with any kind of HTML string and value :这是一种更令人兴奋的方式,它适用于任何类型的 HTML 字符串和value

var tmp_ = document.createElement('div');
tmp_.innerHTML = htmlString;
tmp_.children[0].setAttribute('value', '');

htmlString = tmp_.innerHTML;

DEMO演示

I'd suggest not using a regex for this, but, instead, some pretty simple JavaScript:我建议不要为此使用正则表达式,而是使用一些非常简单的 JavaScript:

var inputs = document.getElementsByTagName('input');
alert(inputs.length);
for (i=0; i<inputs.length; i++){
    //inputs[i].setAttribute('value',''); or you can use the following line instead...
    inputs[i].value = '';
}
  1. JS Fiddle demo (using first line) . JS Fiddle 演示(使用第一行)
  2. JS Fiddle demo (using second line) . JS Fiddle 演示(使用第二行)

If you are using javascript libraries:如果您使用的是 javascript 库:

Mootools version: Mootools 版本:

let say you have a field with the id=test , you can do the following :假设您有一个字段 id=test ,您可以执行以下操作:

$('test').set('value','');

Jquery version: jQuery 版本:

$("#test").val("");

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

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