How to use javascript to calculate the length of bytes occupied by UTF-8 encoded strings

I want to calculate the length of the next byte on the page, because it is too long to be inserted into the database, so I am particularly tangled. How to limit the user's input? After researching for a long time, I finally found a relatively satisfactory calculation method.
Here is the byte length used to calculate the UTF-8 encoding.

Keyword: How to use js, javascript to calculate the length of bytes occupied by UTF-8 encoded strings.
function getStrLeng(str) {
		var realLength = 0;
		var len = str.length;
		var charCode = -1;
		for (var i = 0; i <len; i ++) {
			charCode = str.charCodeAt(i);
			if (charCode >= 0 && charCode <= 128) {
				realLength += 1;
			} else {
				if (charCode < 2048) {
					realLength += 2;
				} else {
					if (charCode < 65536) {
						realLength += 3;
					} else {
                                                //Being lazy here, all the others are counted as 6 bytes. Calculating Chinese and English, this calculation method should be enough.
						realLength += 6;
					}

				}
			}
		}
		return realLength;
	}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326709242&siteId=291194637