2017-06-01 200 views
-2

如何刪除(或隱藏)字符串中的字符,例如: 我有20個字符的字符串,我需要從15中刪除所有字符。 我有一個想法,但不認爲它正確:建立兩款不同類別,一款具有15個字符,第二個沒有關係,並刪除/隱藏第二款 例如:從字符串中的某個字符中刪除字符

var count; 
    count = $('#mydiv').text().length; 
    if (count => 15) { 
    } 
+0

硬從你想要完成的工作中弄明白什麼是什麼。你的html看起來像什麼樣,期望的結果是什麼。請花幾分鐘時間閱讀[ask]和[mcve] – charlietfl

+1

看看[substr](https://www.w3schools.com/jsref/jsref_substr.asp) – myfunkyside

+2

Dupe of https://stackoverflow.com/問題/ 952924/javascript-chop-slice-trim-off-last-character-in-string – j08691

回答

0

使用string.substr

var str = "Hello world!"; 
var res = str.substr(0, 5); // returns Hello 
0

使用slice功能 - string.slice(start, end)

var res = str.slice(0, 16);

+0

值得注意 - ['String.slice和String.substr?'之間的區別](https://stackoverflow.com/a/ 2243835/104380) – vsync

+0

爲什麼你再次評論我的鏈接,並說我已經說過了? – vsync

+0

我通常使用切片的字符串和拼接陣列 –

0

通過CSS:

https://css-tricks.com/snippets/css/truncate-string-with-ellipsis/

.truncate { 
    width: 250px; // or any other width 
    white-space: nowrap; 
    overflow: hidden; 
    text-overflow: ellipsis; 
} 

通過lodash

_.truncate('hi-diddly-ho there, neighborino'); 
// => 'hi-diddly-ho there, neighbo...' 

_.truncate('hi-diddly-ho there, neighborino', { 
    'length': 24, 
    'separator': ' ' 
}); 
// => 'hi-diddly-ho there,...' 

_.truncate('hi-diddly-ho there, neighborino', { 
    'length': 24, 
    'separator': /,? +/ 
}); 
// => 'hi-diddly-ho there...' 

_.truncate('hi-diddly-ho there, neighborino', { 
    'omission': ' [...]' 
}); 
// => 'hi-diddly-ho there, neig [...]' 
1

您正在尋找substring()方法。

var text = "this is a super long string."; 
var shortText = text.substring(0, 15); 
// shortText now is "this is a super"