Rumah  >  Soal Jawab  >  teks badan

在《javascript语言精粹》一书中,js正则表达式剔除重复的单词出错,什么原因?

以下是我按照《javascript语言精粹》一书中的代码写的demo,我想做的事情是历遍文本,把文本中出现的所有单词以只出现一次的形式打印出来(我不知道书中说的“doubled_words”是不是这个意思,不管是不是了,我现在想现实我说的这个结果 ),但是好像没达到我的要求,请教了。

<!DOCTYPE HTML>
<html lang="en-US">
<head>
	<meta charset="UTF-8">
	<title></title>
	
	<style type="text/css">
		#test1,#test2{width:500px;height:200px;border:1px solid #00f;margin-bottom:20px;}
	</style>
	<script type="text/javascript">
	window.onload = function () {
		var test1 = document.getElementById('test1'),
		    test2 = document.getElementById('test2'),
		    textSource = test1.innerHTML,
		    textEscape;
		var textRegExp = /([A-Za-z\u00C0-\u1FFF\u2800-\uFFFD'\-]+)\s+\1/g;//定义一个重复的单词
		textEscape = textSource.replace(textRegExp,"$1");
		test2.innerHTML = textEscape;
		
	}
	</script>
</head>
<body>
	<p id="test1">activity Sizzle It! is is the expert in producing sizzle reels that capture your message and captivate your audience — all with creativity and style.  expert sizzle reels that capture</p>
	<p id="test2"></p>
</body>
</html>

注:我要的效果是:

<p id="test2">activity Sizzle It! is the expert in producing reels that capture your message and captivate audience — all with creativity style.</p>
天蓬老师天蓬老师2749 hari yang lalu1057

membalas semua(1)saya akan balas

  • 大家讲道理

    大家讲道理2017-04-10 12:43:49

    不知道你说的“没达到要求”是指什么,不过这个正则,确实是去除重复单词了。

    var textRegExp = /([A-Za-z\u00C0-\u1FFF\u2800-\uFFFD'\-]+)\s+\1/g;//定义一个重复的单词

    文字匹配后的+,会有点错误,可能导致两个相邻的不同单词,前一个单词的结尾和后一个单词的开头的相同字母被删除。
    改成

    /([A-Za-z\u00C0-\u1FFF\u2800-\uFFFD'\-]{2,})\s+\1/g

    会好点

    balas
    0
  • Batalbalas