【问题标题】:Simple replace with user input in JavaScript用 JavaScript 中的用户输入简单替换
【发布时间】:2015-08-11 02:53:13
【问题描述】:

我正在尝试创建一个“查找和替换”函数,该函数从 Form 元素中获取两个值(替换和替换),然后替换 DIV 中所有出现的“替换”。之后,我希望它显示带有替换字数的警报。 试图通过for 循环到达那里,但出了点问题。使用纯 JS,我对 jQuery 太陌生了。

function wordReplace()
{
    var replaced = document.getElementById('replaced').value.toLowerCase;
    var replacement = document.getElementById('replacement').value;
    var workArea = document.getElementById('main').innerHTML;
    for (var r=0; r<workArea.lenght; r++)
    {
        if (workArea[r].value.toLowerCase == 'replaced')
        {
            workArea[r].value.replace('\breplaced', 'replacement')
            alert(workArea[r].value.replace('replaced', 'replacement').length)
        }
    }
}

这是我的表单代码,以防万一:(忽略&lt;input type="submit" onclick="replacerHide();"/&gt; - 它用于不同的功能,现在可以使用)

<form> 
   <label for="replaced" class="labelInline">Słowo szukane</label>
   <input type="text" name="replaced" id="replaced"/>
   <label for="replacement" class="labelInline">Zamiennik</label>
   <input type="text" name="replacement" id="replacement"/>             
   <input type="submit" onclick="replacerHide();"/>         
</form>      

我在这里(在我的一个类似问题中)读到我应该熟悉regex,我做到了。但不知道如何应用它来解决我的问题。我很确定我在这里使用for 循环,但除此之外我是空的:/

我们将不胜感激所有和任何帮助。

编辑 - 更正完整的工作代码

function wordReplace()
    {
        var div = document.getElementById('main');
        var find = document.getElementById('replaced').value;
        var replace = document.getElementById('replacement').value;

        var re_Find = new RegExp(find, 'gi');
        var matches = div.innerHTML.match(new RegExp(find, 'gi'));

        if (matches) 
            {
                div.innerHTML = div.innerHTML.replace(re_Find, replace);
            }

            matches = matches ? matches.length : 0;
            alert(matches);
     }

对于Form

<div id="form">
        <form id="formularz"> 
            <label for="replaced" class="labelInline">Słowo szukane</label>
            <input type="text" name="replaced" id="replaced"/>
            <label for="replacement" class="labelInline">Zamiennik</label>
            <input type="text" name="replacement" id="replacement"/>                
            <button onclick="replacerHide(); wordReplace();">Podmień!</button>  
        </form>

现在它正在按预期工作:)

【问题讨论】:

  • 控制台输出说什么?我看到 workArea.lenght ,因为我知道它应该是“长度”,所以你的代码应该产生错误
  • 请注意,仅调用 .replace()(如在您的内部循环中)不会更改您调用它的字符串。您需要使用来自.replace() 的字符串returned
  • 更正了错字,但即使它仍在代码控制台中也没有给我任何错误。

标签: javascript html regex forms replace


【解决方案1】:

尝试一些正则表达式。

function replace(find, replace, haystack) { 
    return haystack.replace(new RegExp(find,"gmi"),replace);
    }
function count(find, haystack) { 
        return haystack.match(new RegExp(find,"gmi")).length;
    }
window.alert(replace ("hello","bye","hello world? Hello person! and hello universe!"));
window.alert("Number of matches: "+count("hello","hello world? Hello person! and hello  universe!"));

【讨论】:

  • 所有这些。它匹配所有行上的所有字符串,不区分大小写。如果您运行 sn-p,您会看到它已经替换了所有 3 个 hello。要使其区分大小写,请删除 Regexp 对象中的 i。
  • 来自 OP:“之后我希望它显示一个带有替换字数的警报。”
  • 啊,错过了。添加了计数功能。
【解决方案2】:

Regular expressionsreplace 是你这样的朋友

通过将选项gi 指定给RegExp 构造函数,您可以消除检查字符大小写的需要(i 表示不区分大小写)。 g 表示“全局”,并告诉正则表达式您要对找到的每个 find 实例重复替换(默认情况下,它将替换第一个然后停止)。

// Grab all of the necessary data
var div = document.getElementById('main');
var find = document.getElementById('replaced').value;
var replace = document.getElementById('replacement').value;

// Create our regular expression
var re_Find = new RegExp(find, 'gi');

// Get everything from the div's innerHTML that matches our regular expression
// (this will result in an array of strings, all of which are exactly
// the same as "find")
var matches = div.innerHTML.match(re_Find);

// If there were any matches, use the same regular expression to
// perform the actual replace and update the div
if (matches) {
  div.innerHTML = div.innerHTML.replace(re_Find, replace);
}

// Grab the count of matches that were found and alert the user
matches = matches ? matches.length : 0;
alert(matches);

【讨论】:

  • 按照你的建议做了,遗憾的是 - 无济于事。甚至没有错误。我开始认为问题可能出在其他地方,但在哪里? ://
  • 尝试将 console.log(find, replace, div.innerHTML) 放在前 3 个 var 声明之后,并在控制台中查看它们包含的值。
  • 控制台不返回任何内容。我的意思是它完全是空的。其他功能正常。
  • 我做了一个jsbin给你玩..
  • 我在没有 jQuery 的情况下修复了它。事情是我在不知不觉中重新输入了您的提示并在var find = document.getElementById('replaced').value; 中打错了(替换而不是正确替换)。但现在一切正常。我会在几秒钟内用正确的代码更新问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-28
  • 2021-05-01
  • 2012-11-04
  • 2019-04-22
  • 1970-01-01
  • 2017-11-15
  • 1970-01-01
相关资源
最近更新 更多