我需要在此代码中添加一个条件:
如果插入的值开头不包含符号#
(例如:#stackoverflow
),则在提交时将插入#
。如果该值类似于#stackoverflow
,则无需放置#
。
form.on("submit", () => {
const networkElement = form.closest(".network");
const channel = form.find("input[name='channel']").val();
const key = form.find("input[name='key']").val();
const existingChannel = utils.findCurrentNetworkChan(channel);
if (existingChannel.length) {
existingChannel.trigger("click");
} else {
socket.emit("input", {
text: `/join ${channel} ${key}`,
target: networkElement.find(".lobby").data("id"),
});
}
closeForm(networkElement);
return false;
});
答案 0 :(得分:0)
您可以只检查字符串的第一个字符。假设您正在引用channel变量,则可以执行以下操作:
form.on("submit", () => {
const networkElement = form.closest(".network");
const channel = form.find("input[name='channel']").val();
const key = form.find("input[name='key']").val();
const existingChannel = utils.findCurrentNetworkChan(channel);
//Below is the logic to tell if the channel variable doesn't have the # sign in the
//beginning
if (channel.substring(0,1) !== '#') {
channel = '#' + channel;
}
//The code above checks if the first character isn't the # sign and if it isn't,
//It adds it to the beginning of the string
if (existingChannel.length) {
existingChannel.trigger("click");
} else {
socket.emit("input", {
text: `/join ${channel} ${key}`,
target: networkElement.find(".lobby").data("id"),
});
}
closeForm(networkElement);
return false;
});