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

时间:2015-04-07 00:57:15

标签: javascript regex

这是我的搜索和替换我想出来的。如何合并注释或警告来描述模式和输入的功能框?任何建议表示赞赏!

<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>

1 个答案:

答案 0 :(得分:0)

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

Uncaught SyntaxError: Unexpected reserved word

它似乎是一个Java类,它不会在浏览器中运行,除非你使用像jsp这样的技术。

有一些库已经会像这样做字符串。尝试使用stringjs:http://stringjs.com/。但是,如果你想在整个页面上运行它,你需要解析更复杂的DOM(对字符串这样做更容易)。

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