Javascript搜索和替换需要包含更多内容

Javascript search and replace need to incorporate more

本文关键字:包含更 搜索 替换 Javascript      更新时间:2023-09-26

这是我的搜索和替换。如何合并注释或警报来描述模式和输入的功能框?欢迎提出任何建议!

<html>
<head>
<title> Search & Replace</title>
</head>
<body>
<script language="javascript">
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class StringReplace {
    public static void main(String[] args) {
        String source = "The quick blue bird flies over the brown baseball   field.";
        String find = "blue";
        String replace = "brown";
        //
        // Compiles the given regular expression into a pattern
       //
       Pattern pattern = Pattern.compile(find);
       //
       // Creates a matcher that will match the given input against the pattern
       //
        Matcher matcher = pattern.matcher(source);
        //
        // Replaces every subsequence of the input sequence that matches the
        // pattern with the given replacement string
        //
        String output = matcher.replaceAll(replace);
        System.out.println("Source = " + source);
          System.out.println("Output = " + output);
    }
} 
</script>
</body>
</html>

这是无效的javascript,如果您尝试在导入时加载此页面,控制台将抛出错误:

Uncaught SyntaxError: Unexpected reserved word

它看起来是一个Java类,除非使用jsp之类的技术,否则不会在浏览器中运行。

有一些库已经可以做这样的字符串了。例如,尝试字符串:http://stringjs.com/.然而,如果您想在整个页面上运行此操作,则需要解析更复杂的DOM(对字符串执行此操作要容易得多)。

对于使用输入,您应该更深入地研究html。有许多文本框和文本字段选项,您可以将它们绑定到javascript。