在JavaScript中:
"ab abc cab ab ab".replace(/\bab\b/g, "AB");
Run Code Online (Sandbox Code Playgroud)
正确地给了我:
"AB abc cab AB AB"
Run Code Online (Sandbox Code Playgroud)
当我使用utf-8字符时:
"?? ??? ??? ?? ??".replace(/\b??\b/g, "AB");
Run Code Online (Sandbox Code Playgroud)
在字边界运营商似乎并没有工作:
"?? ??? ??? ?? ??"
Run Code Online (Sandbox Code Playgroud)
这个问题有方法解决吗?
需要在{}中的unicode字符串中放置unicode单词列表.有我的代码:
var txt = "¿One;one oneé two two two two two twö twöu three;;twä;föur?";
var re = new RegExp("(^|\\W)(one|tw|two two|two|twöu|three|föur)(?=\\W|$)", "gi");
alert(txt.replace(re, '$1 {$2}'));
Run Code Online (Sandbox Code Playgroud)
它返回:
¿{One}; {one} {one}é{two two} {two two} {two} {tw}ö{tw}öu{three} ;; {tw}ä; {föur}?
但应该是:
¿{One}; {one}oneé{two two} {two two} {two}twö{twöu} {three} ;;twä; {föur}?
我做错了什么?
有没有一种方法可以将这种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),因为要查找的这些替换词是通过函数调用传递的。
更新:要尝试上面的代码,请用上面的代码替换此处 …