web関連

【jquery】文字列の特定の文字をHTMLタグで囲む方法

文字列の中から特定の文字を探してspanタグで囲む必要があったときの備忘録

特定の文字をHTMLタグで囲む方法

特定のHTML要素を囲むならwrap()とか使えばできるんだけどテキストとなるとslice()を使って文字列を分割してHTMLタグを挿入する必要性があるみたい

<p>これはテストです</p>

<script>
jQuery(function($){
	const elem = $('p');
	const elemTxt = elem.html();// 対象の文字列を取得
	const elemTxtNum = elemTxt.length;// 対象の文字列の長さを取得
	const targetTxt = 'テスト';// 囲むターゲット
	const txtLength = targetTxt.length;// ターゲットの文字列の長さを取得
	const searchNum = elemTxt.indexOf(targetTxt);// 何文字目にあるか取得(0~)
	const firstStr = elemTxt.slice(0, searchNum);// これは
	const targetStr = elemTxt.slice(searchNum, searchNum+txtLength);// テスト
	const secondStr = elemTxt.slice(searchNum+txtLength, elemTxtNum);// です
	// 結合
	elem.html(firstStr + '<span style="font-size:30px;">' + targetStr + '</span>' + secondStr);
});
</script>

これで該当のテキストをHTMLタグで囲むことができる

備忘録書いてて気づいたんだけどreplace()を使ったほうが短く書けるから使うならreplace()の方がいいかも…リンク↓

複数の要素の中の特定の文字をHTMLタグで囲む方法

複数のテキストがあるならeach()を使ってループ処理をする

<p>これはテストです</p>
<p>テストですこれは</p>
<p>ですこれはテスト</p>

<script>
jQuery(function($){
	$('p').each(function(i) {
		const elem = $(this);
		const elemTxt = elem.html();
		const elemTxtNum = elemTxt.length;
		const targetTxt = 'テスト';
		const txtLength = targetTxt.length;
		const searchNum = elemTxt.indexOf(targetTxt);
		const firstStr = elemTxt.slice(0, searchNum);
		const targetStr = elemTxt.slice(searchNum, searchNum+txtLength);
		const secondStr = elemTxt.slice(searchNum+txtLength, elemTxtNum);
		console.log(firstStr);
		// 結合
		elem.html(firstStr + '<span style="font-size:30px;">' + targetStr + '</span>' + secondStr);
	});
});
</script>

Leave a Comment

入力エリアすべてが必須項目です。メールアドレスが公開されることはありません。

内容をご確認の上、送信してください。