如何刪除(或隱藏)字符串中的字符,例如: 我有20個字符的字符串,我需要從15中刪除所有字符。 我有一個想法,但不認爲它正確:建立兩款不同類別,一款具有15個字符,第二個沒有關係,並刪除/隱藏第二款 例如:從字符串中的某個字符中刪除字符
var count;
count = $('#mydiv').text().length;
if (count => 15) {
}
如何刪除(或隱藏)字符串中的字符,例如: 我有20個字符的字符串,我需要從15中刪除所有字符。 我有一個想法,但不認爲它正確:建立兩款不同類別,一款具有15個字符,第二個沒有關係,並刪除/隱藏第二款 例如:從字符串中的某個字符中刪除字符
var count;
count = $('#mydiv').text().length;
if (count => 15) {
}
使用string.substr
var str = "Hello world!";
var res = str.substr(0, 5); // returns Hello
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;
}
_.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 [...]'
您正在尋找substring()方法。
var text = "this is a super long string.";
var shortText = text.substring(0, 15);
// shortText now is "this is a super"
如果你知道你要刪除,然後只是.replace取代它什麼()不知道你的隱藏字符意味着什麼。似乎所有的答案是你的問題可能的解決方案,雖然https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
我建議你看一看的子支持頁面:
https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/String/substring
的jsfiddle與子使用:
https://jsfiddle.net/zdLdk6Lj/
var divtext = $('#mydiv').text();
$('#mydiv').text(divtext.substring(0,15));
硬從你想要完成的工作中弄明白什麼是什麼。你的html看起來像什麼樣,期望的結果是什麼。請花幾分鐘時間閱讀[ask]和[mcve] – charlietfl
看看[substr](https://www.w3schools.com/jsref/jsref_substr.asp) – myfunkyside
Dupe of https://stackoverflow.com/問題/ 952924/javascript-chop-slice-trim-off-last-character-in-string – j08691