有没有一种方法可以将这种replace
方法应用于一般的Unicode文本(这里是阿拉伯语)?在下面的示例中,虽然替换整个单词在英语文本上效果很好,但是它无法检测到,因此替换了阿拉伯单词。我添加了u
作为标记以启用unicode解析,但这没有帮助。在下面的阿拉伯语示例中,单词?????? 应该替换,但不能替换???????,但这不会发生。
<!DOCTYPE html>
<html>
<body>
<p>Click to replace...</p>
<button onclick="myFunction()">replace</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "????? ?????? ???????? ?? ?????? ???????";
var rep = '??????';
var repWith = '?????';
//var str = "the sun and the stars, then the starsz and the day";
//var rep = 'stars';
//var repWith = 'night';
var result = str.replace(new RegExp("\\b"+rep+"\\b", "ug"), repWith);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
并且,无论您提供什么解决方案,都请使用上面代码中的变量(上面的变量rep
),因为要查找的这些替换词是通过函数调用传递的。
更新:要尝试上面的代码,请用上面的代码替换此处的代码。
模式\\bword\\b
可以表示为(^|[A-Za-z0-9_])word(?![A-Za-z0-9_])
模式,当需要替换匹配时,需要添加$1
在替换模式前添加。
由于您需要使用 Unicode,因此使用支持任何基本 Unicode 字母的“速记”符号的XRegExp库是有意义的。\\pL
您可以将A-Za-z
上面的模式替换为这个\\pL
:
var str = "\xd8\xa7\xd9\x84\xd8\xb4\xd9\x85\xd8\xb3 \xd9\x88\xd8\xa7\xd9\x84\xd9\x82\xd9\x85\xd8\xb1 \xd9\x88\xd8\xa7\xd9\x84\xd9\x86\xd8\xac\xd9\x88\xd9\x85\xd8\x8c \xd8\xab\xd9\x85 \xd8\xa7\xd9\x84\xd9\x86\xd8\xac\xd9\x88\xd9\x85 \xd9\x88\xd8\xa7\xd9\x84\xd9\x86\xd9\x87\xd8\xa7\xd8\xb1";\r\nvar rep = \'\xd8\xa7\xd9\x84\xd9\x86\xd8\xac\xd9\x88\xd9\x85\';\r\nvar repWith = \'\xd8\xa7\xd9\x84\xd9\x84\xd9\x8a\xd9\x84\';\r\n\r\nvar regex = new XRegExp(\'(^|[^\\\\pL0-9_])\' + rep + \'(?![\\\\pL0-9_])\');\r\nvar result = XRegExp.replace(str, regex, \'$1\' + repWith, \'all\');\r\nconsole.log(result);
Run Code Online (Sandbox Code Playgroud)\r\n<script src="https://cdnjs.cloudflare.com/ajax/libs/xregexp/3.1.1/xregexp-all.min.js"></script>
Run Code Online (Sandbox Code Playgroud)\r\n@mohsenmadi 更新:\n要集成到 Angular 应用程序中,请按照以下步骤操作:
\n\nnpm install xregexp
将库添加到package.json
import { replace, build } from \'xregexp/xregexp-all.js\';
let regex = build(\'(^|[^\\\\pL0-9_])\' + rep + \'(?![\\\\pL0-9_])\');
let result = replace(str, regex, \'$1\' + repWith, \'all\');