我要放置的歌曲标题-任何带有单引号的歌曲都会破坏代码-例如,当我尝试广告“ That's Alright”时,它会被注册为“ That”,因为'会中断。这是孤立的代码行。有人可以推荐一种修补程序,将其替换为\吗?
"<input type='hidden' name='title' value='"+val.sources[0].title+"'>"+
尝试了W3 Schools
的代码变体var str = "Visit Microsoft!";
var res = str.replace("Microsoft", "W3Schools");
但我相信语法已关闭...
"<input type='hidden' name='title' value='"+val.sources[0].title+"'>"+
我希望隐藏字段的值不会在'
处中断<?php if($playlist!='fav' && $membership == '2'){ // REMOVED $list ?>
"<form id='addFavorite' action='process_fav_add_pro_preview.php?p=<?php echo $playlist; ?>' method='post'><input type='hidden' name='favid' value='"+val.sources[0].track_id+"'>"
+
"<input type='hidden' name='mediatype' value='"+val.sources[0].media+"'>"+
"<input type='hidden' name='title' value='"+val.sources[0].title+"'>"+
"<input type='hidden' name='artist' value='"+val.sources[0].artist+"'>"+
"<input type='hidden' name='source_url' value='"+val.sources[0].src+"'>"+
"<input type='hidden' name='credits' value='"+val.sources[0].credits+"'>"+
"<input type='hidden' name='user' value='<?php echo $id; ?>'>"+
"<input type='hidden' name='playlists' value='<?php echo $playlist; ?>'>"+
"<button class='playlist-favorite' id='sub'><i class='fa fa-heart faa-flash animated-hover' style='color:#ff4444'></i></button>"+
"</form>"
+
<? } ?>
答案 0 :(得分:1)
要接受其中带有单引号或单引号的字符串,可以使用以下方法:
function escapeRegExp(text) {
return text.replace(/[']/g, '\\$&');
}
这是以下方法的一种变体:
function escapeRegExp(text) {
return text.replace(/[-[\]{}()*+?.,'\\^$|#]/g, '\\$&');
}
参考this问题,在Stack Overflow。
如果您将值传递为escapeRegExp("That's alright")
,则它将变为That\'s alright
更新: 这是您可以尝试做的事情:
$("input[name='title']").each(function(){
var text = $(this).val();
$(this).val(escapeRegExp(text));
});
function escapeRegExp(text) {
return text.replace(/[']/g, '\\$&');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' name='title' value="That's alright">
在这里,我刚刚将类型更改为text
,以便输出可读,但是如果再次将其更改回hidden
,代码将起作用。