javascript中string.prototype替换无效

查看:91
本文介绍了javascript中string.prototype替换无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

console中没有出错信息,代码如下:

<!DOCTYPE html>
<meta charset="UTF-8">
<div id="con">http://www.xiami.com/song/1769509599</div>
<script>
$=function(i){return document.querySelector(i)};
String.prototype.enHtml=function(){
    return this
    .replace(/(^\s*)|(\s*$)/g,'')
    .replace(/(http\:\/\/|)(ww[0-9]{1}\.sinaimg\.cn\/)(?:[\w]{4,10})(\/[\w]{16,32}\.)(gif|jpg|jpeg|png)/g,"http://$2bmiddle$3$4")
    .replace(/http:\/\/www\.xiami\.com\/song\/([0-9]{5,12})[\?\w\.\=]*/g,'<a href="//www.xiami.com/song/$1" target="_blank" class="xiami">http://www.xiami.com/song/$1</a>')
    .replace(/(http\:\/\/[0-9A-Za-z\/.#&!?%:;=_]+\.)(gif|jpg|jpeg|png)/g,"<img src=\"$1$2\">")
    .replace(/(^|[^\"\'\]>])(http|ftp|mms|rstp|news|https|telnet)\:\/\/([0-9A-Za-z\/.#&!?%:;=\-_]+)/g,'$1<a href="$2://$3" rel="external nofollow noreferer" class="link" target="_blank">$2://$3</a>')
    .replace(/(@)([\u4e00-\u9fa5\u0800-\u4e00A-Za-z0-9\-_]{2,32})/ig,"<span class=\"at\">$1$2</span>")
    .replace(/\n/g,'<br>')
};
$('#con').innerHTML.enHtml();
</script>

解决方案

我猜你是想替换innerHTML自身对吧?

那你要注意了,replace并不会修改自身,而是返回一个新的字符串

文档replace

这篇关于javascript中string.prototype替换无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆