我试图创建一个函数来替换一些字母,这样我就可以在不同的地方调用同一个函数。到目前为止这是我创造的。无法使函数成为返回主代码的数据。
$(document).ready(function() { MyFunction("Hello"); alert(text); }); function MyFunction(text) { var text = text.replace("h","m"); return text; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
忽略区分大小写
function MyFunction (text) { return text.replace(/h/i, "m"); }
replace("h","m");
你想用m代替h
replace("H","m");
因为没有小的 h 在世界上。而是找一个大的 H :
h
H
$(document).ready(function() { let text = MyFunction("Hello"); console.log(text); }); function MyFunction(t) { let text = t.replace("h","m"); return text }
或者改用regex忽略该情况: t.replace(/h/ig,"m")
t.replace(/h/ig,"m")
将函数调用放入警报或将其设置为变量,然后如果要替换大写 H ,使用 小时 不 h 在你的职责范围内。
小时
$(document).ready(function() { alert(MyFunction("Hello")); }); function MyFunction(text) { var text = text.replace("H","m"); return text; }