我正在尝试创建一个函数来替换一些字母,以便可以在各个地方调用相同的函数。到目前为止,这就是我创造的。无法使函数将数据返回主代码。
$(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>
答案 0 :(得分:1)
这是因为单词中没有小的h
。而是寻找较大的H
:
$(document).ready(function() {
let text = MyFunction("Hello");
console.log(text);
});
function MyFunction(t) {
let text = t.replace("h","m");
return text
}
或者使用正则表达式来忽略大小写:
t.replace(/h/ig,"m")
答案 1 :(得分:1)
将函数调用放在警报中或将其设置为变量,然后如果要替换大写的H
,请在函数中使用H
而不是h
。
$(document).ready(function() {
alert(MyFunction("Hello"));
});
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>
答案 2 :(得分:0)
replace("h","m");
将h替换为m
replace("H","m");
答案 3 :(得分:0)
忽略大小写
function MyFunction (text) {
return text.replace(/h/i, "m");
}