特定の文字列を置換するjQuery
今日は、画面サイズによって文字列を置換する jQueryを作成しました。
[ 作成理由 ]
モバイルデバイス表示時のレイアウト切り替えに伴い、
表示テキストを変更したかったため。
特定の文字列を置換するjQuery
仕様
画面サイズが1,024 px 以下の時、
actionクラスの「See more」テキストを「モバイル時テキスト」に置換します。
コード
$(function(){ $('.action').each(function(){ var w = $(window).width(); var x = 1024; var txt = $(this).text(); alert($('.action').html()); if (w <= x) { var txt = $(this).text(); alert($('.action').html()); $(this).text( txt.replace(/See more/g,"モバイル時テキスト") ); } }); }); });
補足解説
replace(/置換対象文字列/g, ‘置換後の文字列’);
【参考記事】
jQueryで現在のウィンドウサイズの取得と判定をして処理を変えるやり方 | bl6.jp :
http://bl6.jp/web/javascript/change-process-get-window-size/
jQuery 特定文字列や特定要素の削除及び置換方法 | Stronghold Archive :
https://zxcvbnmnbvcxz.com/jq-remove-replace/index.html
上記コードご利用時には、クラス名やテキストを任意の値にご変更ください。
以上、ご参考まで。