Last active
May 9, 2021 16:55
-
-
Save Yoxem/095cdeb8b355688bd0ab46d1617423af to your computer and use it in GitHub Desktop.
a test for how to insert a string or html parts after ith character in innerHTML of a HTML element.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<!-- | |
這是示範「如何在某個 HTML parts 的第幾個字插入字串(或是 HTML 標籤的範例)」 | |
License : Public Domain | |
--> | |
<head> | |
<title>test for input string</title> | |
</head> | |
<body> | |
<div id="test">台灣 ê siaⁿ-im,tī<b> 佗位? Lorem <i>ipsum</i></b><i> dolor sit</i> amet, inis me Johano agus mar sin de.</div> | |
<button id="click">點我</button> | |
</body> | |
<script type="text/javascript"> | |
var test = document.getElementById("test"); | |
var click = document.getElementById("click"); | |
var col = 35; // the position (after ith character) you want to add the string. | |
var string = "<br/>"; // the string you want to add | |
col = getrealcol(col, test.innerHTML); | |
click.addEventListener("click", function(e) { | |
test.innerHTML = test.innerHTML.replace(RegExp("(.{" + col + "})"), "$1<br/>"); | |
}); | |
var s1 = "12334<b>1234</b>11234" | |
function getrealcol(n, str){ | |
var arr = str.split(RegExp("(<[^<>]+>)")).map((x)=>({cont : x , len : x.length})); | |
var j = 0; | |
var k = 0; | |
for (var i=0;i<arr.length;i++){ | |
if (arr[i].cont.match(/^[<]/)){continue;} | |
else{ | |
if(n > arr[i].len){n = n - arr[i].len} | |
else{j = i; k = n; break;} | |
} | |
}; | |
var res_col = 0 | |
for (var i=0;i<j;i++){ | |
res_col += arr[i].len; | |
} | |
res_col += k; | |
return res_col; | |
} | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment