如何使用javascript从srting获得前8个char和最后8个char?
我将此代码用于php,如何将此代码应用于javascript?
$file_name_length = mb_strlen($file_name, 'UTF-8');
$first_char_position_last_8_char_file_name= $file_name_length-8;
$first_8_char_file_name_display = mb_substr($file_name, 0, 8,"utf-8");
$last_8_char_file_name_display = mb_substr($file_name, $first_char_position_last_8_char_file_name, 8,"utf-8");
答案 0 :(得分:5)
您可以使用String.prototype.substr():
var data = '12345678whatever87654321';
data.substr(0, 8); // 12345678
data.substr(-8); // 87654321
答案 1 :(得分:2)
您可以使用以下子字符串来执行此操作:
var str = "some string with many chars";
var newstr=str.substring(0,8)+str.substr(str.length-8);
答案 2 :(得分:0)
您可以使用String.slice或String.substring
在你的情况下,这应该有效:
var string = 'Hello nice nice world';
// with substring
console.log(string.substring(0, 8), string.substring(string.length - 8, string.length)); // Hello ni ce world
// with slice
console.log(string.slice(0, 8), string.slice(string.length - 8, string.length)); // Hello ni ce world
答案 3 :(得分:0)
使用相同的变量名称:
var file_name_length = file_name.length;
var first_char_position_last_8_char_file_name= file_name_length - 8;
var first_8_char_file_name_display = file_name.substr(0, 8);
var last_8_char_file_name_display = file_name.substr(first_char_position_last_8_char_file_name, 8);