简体   繁体   English

如何在 javascript 的末尾修剪不需要的连续字符串?

[英]How to trim an unwanted continuous string at end in javascript?

I am trying to trim a string with unnecessary characters at the end as below.我正在尝试在末尾修剪带有不必要字符的字符串,如下所示。 I would appreciate either if someone corrects me or provide me an easy approach!!如果有人纠正我或为我提供简单的方法,我将不胜感激!

Expected Result: finalString, Hello ---- TecAdmin预期结果: finalString, Hello ---- TecAdmin

 const longStr = "Hello ---- TecAdmin------------"; function trimString(str) { const lastChar = str[str.length - 1]; if(lastChar === '-') { str = str.slice(0, -1); trimString(str); } else { console.log(str,'finally') return str; } } const finalString = trimString(longStr); console.log('finalString', finalString)

Try this out - replace only 5 or more -试试这个 - 只更换 5 个或更多 -

longStr.replace(/-{5,}/g, '')

Working off Deryck's comments & answer, but allowing for any number of dashes on the end:处理 Deryck 的评论和答案,但最后允许任意数量的破折号:

 const longStr = "Hello ---- TecAdmin------------"; var thing = longStr.replace(/-*$/g, ''); console.log(thing);

use split to split the string into an array, then use pop however many times to remove characters at the end.使用 split 将字符串拆分为一个数组,然后使用 pop 但是多次删除末尾的字符。 you can test the last character each time and use pop if its a "-"您可以每次测试最后一个字符,如果它是“-”,则使用 pop

//js
const longStr = "Hello ---- TecAdmin------------";
let splitLongStr = longStr.split('');

for (let i=0; i<splitLongStr.length; i++) {
  splitLongStr.pop();
}

let longStrChopped = splitLongStr.join('');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM