Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[js] 第3天 去除字符串中最后一个指定的字符 #9

Open
haizhilin2013 opened this issue Apr 18, 2019 · 129 comments
Open

[js] 第3天 去除字符串中最后一个指定的字符 #9

haizhilin2013 opened this issue Apr 18, 2019 · 129 comments
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

[js] 第3天 去除字符串中最后一个指定的字符

@haizhilin2013 haizhilin2013 added the js JavaScript label Apr 18, 2019
@undefinedYu
Copy link
Contributor

function delLast (str,del) {
if (tpeof str !== 'string') {
alert('请确认要删除的对象为字符串!');
retrun false;
} else {
let index = str.lastIndexOf(del);
str.substring(0,index ) + str.substring(index+1,str.length);
}
}
用的是张震的方法

@yxkhaha
Copy link

yxkhaha commented Apr 19, 2019

function trim(str) { if(typeof str === 'string'){ var trimStr = str.substring(0,str.length-1) } return trimStr; }

@linghucq1
Copy link

🐶

function delLast(str, target) {
  return str.split('').reverse().join('').replace(target, '').split('').reverse().join('');
}

const str = delLast('asdfghhj', 'h')

console.log(str) // asdfghj 

@tzjoke
Copy link

tzjoke commented May 16, 2019

String.prototype.reverse = function () {
    return this.split('').reverse().join('')
}

String.prototype.removeFirstChar = function (m) {
    return this.replace(m, '')
}

const string = 'emamam, your string'
const removedChar = 'm'
string.reverse().removeFirstChar(removedChar).reverse()

@XIGUATANG
Copy link

function delLast(str,target) {
  let reg =new RegExp(`${target}(?=([^${target}]*)$)`)
  return str.replace(reg,'')
}

@myprelude
Copy link

怎么开始全是正则????@haizhilin2013

@AricZhu
Copy link

AricZhu commented Jun 18, 2019

function delLastStr(str, delStr) {

for (let i = str.length - 1; i >= 0; i --) {
	if (delStr === str[i]) {
		return str.substring(0, i) + str.substring(i+1);
	}
}
return str;

}

@Damon99999
Copy link

function delLast(str, target) {
  return str.split('').reverse().join('').replace(target, '').split('').reverse().join('');
}

const str = delLast('asdfghhj', 'h')

console.log(str) // asdfghj 

1:性能问题
2:太长了

个人见解

@Damon99999
Copy link

var str = "array"
str.substr(0, str .length-1);
str.substring(0, str .length-1);

@bWhirring
Copy link

bWhirring commented Jun 29, 2019

function del(str, n) {
	str = [...str]
	const idx = str.lastIndexOf(n);
	return str.splice(idx, 1).join('');
}

@Raonet
Copy link

Raonet commented Jul 1, 2019

function delLast (str,del) {
if (tpeof str !== 'string') {
alert('请确认要删除的对象为字符串!');
retrun false;
} else {
let index = str.lastIndexOf(del);
str.substring(0,index ) + str.substring(index+1,str.length);
}
}
用的是张震的方法

---楼主typeof打错啦,还有str.substring(0,index ) + str.substring(index+1,str.length);这行应该也要return一下吧,不然成功删除了以后没有返回值

@Konata9
Copy link

Konata9 commented Jul 1, 2019

const removeRight = (str, target) => {
  if (!str || !target) {
    return str;
  }

  const idx = str.lastIndexOf(target);
  if (idx > -1) {
    return str.slice(0, idx) + str.slice(idx + 1);
  } else {
    return str;
  }
};

const str = "aaa1 bc de a 2";

console.log(removeRight(str, "e"));
console.log(removeRight(str, "a"));
console.log(removeRight(str, "c"));

@DarthVaderrr
Copy link

思路:循环,从字符串尾部开始移动,直到匹配到的第一个目标字符,将它删除,退出循环,循环结束或退出后,返回字符串。

@zhuoyan
Copy link

zhuoyan commented Jul 4, 2019

var filterLast = function(str, del) {
    const index = str.lastIndexOf(del);
    if(index > -1) {
        str = [...str];
        str.splice(index, 1);
        return str.join('');
    }
    return str;
}

@15190408121
Copy link

@undefinedYu 借用了一下你的方法稍作修改,让它能输出
var str = "123456789"
function strdelete (str, del) {
if (typeof str !== 'string') {
return false
} else {
var index = str.lastIndexOf(del)
return str.substring(0,index ) + str.substring(index+1,str.length);
}
}
strdelete(str, "9")

@poporeki
Copy link

poporeki commented Jul 4, 2019

function delString(str, delChar) {
    if (!str || typeof str !== 'string' || !delChar || typeof delChar !== 'string') return false;
    let arr = str.split('');
    let idx = arr.lastIndexOf(delChar);
    arr.splice(idx, 1);
    return arr.join('');
  }

@jiuylq
Copy link

jiuylq commented Jul 6, 2019

前面有朋友通过[...str]来实现,没考虑到如果不是单一字符的情况吧
我也来添加一个

function removeLastStr(str, dstr) {
  var arr = str.split(dstr);
  var len = arr.length;
  var nArr = [].concat(arr.slice(0, len-2))
  nArr.push(arr[len-2]+arr[len-1])
  return nArr.join(dstr)
}

@seho-dev
Copy link

lastIndexOf看看最后字的索引,截取即可

@seho-dev
Copy link

function subStrIn(str, value) {
if (typeof str !== "string" || typeof value !== "string") {
throw new Error("非字符串!");
}
let length = str.length;
let lastIndex = str.lastIndexOf(value);
// 截取
return str.substr(0, lastIndex) + str.substr(lastIndex + 1, length);
}

console.log(subStrIn("1234345", "3"));

@zhoufanglu
Copy link

        /**
         *
         * @param string '字符串'
         * @param delItem '删除的字符'
         */
        function delLastItem(string,delItem){
          let arr = string.split('')
          arr.map((item,index)=>{
            if(delItem === item){
              arr.splice(index,1)
            }
          })
          console.log(136,arr.join(''))
        }

delLastItem('12323sdaas2','a')  //输出 '12323sdas2'

@shufangyi
Copy link

function deleteSpecifiedLastCharacter(str, char) {
  if (!char || typeof str !== 'string' || typeof char !== 'string') return str
  return str.replace(new RegExp(`${char}(?=([^${char}]*)$)`), '')
}

@slnzzl
Copy link

slnzzl commented Jul 23, 2019

var a = (str,s)=>{

        var a = str.lastIndexOf(s)

        // console.log(a)

        // console.log(str.substring(0,a))
        // console.log(str.substring(a+1,str.lenth))


      console.log(str.substring(0,a)+(str.substring(a+1,str.lenth))) 






    }

   a('abcdefghgh','g') 

@anncwb
Copy link

anncwb commented Jul 25, 2019

function delLast(str,target) {
  let reg =new RegExp(`${target}(?=([^${target}]*)$)`)
  return str.replace(reg,'')
}

delLast('emamam, your string', 'ur') // =>emamam, your string

@gu-xionghong
Copy link

gu-xionghong commented Jul 25, 2019

function delLastStr(str, delStr) {
  const reg = new RegExp(`^(.*)(${delStr})(.*)$`)
  return str.replace(reg, '$1$3')
}

delLastStr('emamam, your string', 'ur')

@ZhaoYu8
Copy link

ZhaoYu8 commented Jul 26, 2019

// 字符串自带查找字符串最后出现的位置:lastIndexOf
let str = '1  ab c     c   c ca  asdab aaa'
console.log((function (str, keyword) {
  let index = str.lastIndexOf(keyword)
  return index === -1 ? str : str.slice(0, index) + str.slice(index + keyword.length)
})(str, 'ab'))

@IanSun
Copy link

IanSun commented Jul 26, 2019

function removeLastAppearedChar ( string = ``, char = `` ) {
  return string.replace( new RegExp( `${ char }(?=[^${ char }]*$)`, `u` ), `` );
}
function removeLastAppearedChar ( string = ``, char = `` ) {
  const index = string.lastIndexOf( char );
  return -1 < index ?
    string.slice( 0, index ) + string.slice( index + 1 ) :
    string;
}

@AchillesV
Copy link

function removeLast(str,k){
  return str.slice(0,str.lastIndexOf(k)) + str.slice(str.lastIndexOf(k)+1)
}

@wsb260
Copy link

wsb260 commented Jul 30, 2019


const removeLastStr = (str, target) => {
  if (!str || !target) {
    return str;
  }
  if(typeof str !== 'string'){
    alert('输入的对象不是字符串!');
    return false;
  }
  const idx = str.lastIndexOf(target);
  if (idx > -1) {
    return str.slice(0, idx) + str.slice(idx + 1);
  } else {
    return str;
  }
};

@Susie350
Copy link

Susie350 commented Sep 2, 2021

const deleteLastChar = (str, c) => {
let res = str.split('');
res.splice(str.lastIndexOf(c), 1);
return res.join('');
}
deleteLastChar('111a11111a11', 'a')

@HNHED
Copy link

HNHED commented Sep 2, 2021

function removestr(str,target){
let index = str.lastIndexOf(target);
return str.substring(0,index)+str.substring(index+1);
}
console.log(removestr('dsadsadsadjdiasjd','s'));

@zxcdsaqwe123
Copy link

// 去除字符串中最后一个指定的字符
function delLast(str, del) {
let arr = str.split('')
let delnum = -1
for (let i = arr.length; i > 0; i--) {
if(arr[i-1] === del){
delnum = i-1
break
}
}
if(delnum != -1){
arr.splice(delnum,1)
}
return arr.reduce((x,y)=>x+y);
}

console.log(delLast('asavded242%1%f5f6h7h8s9s', '2'))

@zhongxy823
Copy link

function deleteStrLastAppoint (str, appoint) {
if (tpeof str !== 'string') return false
if (tpeof appoint !== 'string') return false
var reverseStr = reverseString(str)
var reverseResult = reverseStr.replace(appoint, '')
return reverseString(reverseResult)
}
function reverseString (str) {
return str.split('').reverse().join('')
}

@xuan-123
Copy link

function delLast(){
}

@amikly
Copy link

amikly commented Oct 21, 2021

lastIndexOf + splice + join方法

function delLastAnyChar(str, char) {
    str = [...str];
    let index = str.lastIndexOf(char);
    str.splice(index, 1);
    return str.join("");
 }

lastIndexOf()方法返回指定元素在数组中的最后一个的索引,如果不存在则返回 -1。从数组的后面向前查找,从 fromIndex 处开始。

splice() 方法通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组。

join() 方法将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串。

数组遍历

let newStr = [];
  function delLastAnyChar(str, char) {
    str = [...str];
    let index = str.lastIndexOf(char);
    str.forEach((v, i) => (i !== index ? newStr.push(v) : false));
    return newStr.join("");
}

forEach()方法对数组的每个元素执行一次给定的函数

正则+substring

let strList = [];
function delLastAnyChar(str, char) {
    let reg = eval(`/${char}/g`);
    // 使用matchAll方法或者exec方法进行全局匹配
    // while(res=reg.exec(str)) strList.push(res)
    for (const i of str.matchAll(reg)) {
        strList.push(i.index);
    }
    let index = strList[strList.length - 1];
    console.log(index);
    return str.substring(0, index) + str.substring(index + 1, str.length);
}

eval() 函数会将传入的字符串当做 JavaScript 代码进行执行

matchAll() 方法返回一个包含所有匹配正则表达式的结果及分组捕获组的迭代器

substring()方法返回一个字符串在开始索引到结束索引之间的一个子集, 或从开始索引直到字符串的末尾的一个子集

正则+replace

function delLastAnyChar(str, char) {
    // [^]就是相当于通配符`.`,([^]*)表示匹配任意长度的字符,并且为获取匹配
    let reg = new RegExp(`^([^]*)(${char})([^]*)$`);
    // console.log(str.match(eval(`/^([^]*)(${char})([^]*)$/`)));
    return str.replace(reg, "$1$3");
}

match() 方法检索返回一个字符串匹配正则表达式的结果

replace() 方法返回一个由替换值(replacement)替换部分或所有的模式(pattern)匹配项后的新字符串

模式可以是一个字符串或者一个正则表达式,替换值可以是一个字符串或者一个每次匹配都要调用的回调函数

如果pattern是字符串,则仅替换第一个匹配项,原字符串不会改变

@July107
Copy link

July107 commented Nov 1, 2021

直接分割字符串然后拼接即可

function deleteLastStr(str, deleteStr){
    if(typeof str === 'string'){
        let num = str.lastIndexOf(deleteStr);
        return str.substr(0, num - 1) + str.substr(num);
    }
}

@tk12138
Copy link

tk12138 commented Nov 4, 2021

let myStr = 'ddfekekdfkdjfioej'
function trim(str, targetStr){
const index = str.lastIndexOf(targetStr)
return str.substring(0, index).concat(str.substring(index+1))
}
console.log(trim(myStr, 'o'))

@baiye0
Copy link

baiye0 commented Dec 30, 2021

function removestr(str,target){
let index = str.lastIndexOf(target);
return str.substring(0,index)+str.substring(index+1);
}
console.log(removestr('dsadsadsadjdiasjd','s'));

@beautifulwhale
Copy link

function delStr(str, target) { return str.split('').reverse().join('').replace(target, '').split('').reverse().join('') } var str = 'abcddf' console.log(delStr(str, 'd'))

@Rednaxela-2
Copy link

//第3天 去除字符串中最后一个指定的字符
//两种方法,任君选择,本鼠鼠觉得自己的答案是最好的捏,有没有好兄弟可以指教下。另,有没有好妹妹给我透啊😋
function removeSubstringByRegexp(str,subString) {
if(!str.includes(subString)) {
return str
}
let reg = new RegExp(${subString}(?=[^(${subString})]*$))
return str.replace(reg,'')
}
function removeSubstringByIndex(str,subString) {
let index = str.lastIndexOf(subString);
return str.slice(0,index).concat(str.slice(index+subString.length,str.length))
}
let str = " i am the king of the king world "
console.log(removeSubstringByRegexp(str,"the"));
console.log(removeSubstringByIndex(str,"king"));

@QiaoIsMySky
Copy link

    function trim(str, del) {
        let strArr = str.split('')
        let indexArr = []
        strArr.forEach((i, index) => {
            if (i == del) {
                indexArr.push(index)
            }
        })
        strArr.splice(indexArr[indexArr.length - 1], 1)
        return strArr.join('')
    }
    console.log(trim('trimm6711m', 'm'));

@13714273163
Copy link

13714273163 commented Feb 8, 2022 via email

@github-cxtan
Copy link

function DeleteCharAt(data, c){
var str = "";
str = data;
let index = str.lastIndexOf(c);
return str.slice(0, index)+str.slice(index+1);
}

@yxllovewq
Copy link

const delLastChar = (str = '', char = '') => {
let id = str.lastIndexOf(char);
if (id !== -1) {
str = str.slice(0, id) + str.slice(id + 1);
}
return str;
}

@kankan-web
Copy link

function clearLastChar(str:string,char:string):string{
  let index = str.lastIndexOf(char)
  let newStr = str.slice(0,index) + str.slice(index+1)
  return newStr
}
clearLastChar('Hello World','l')

@wenxd
Copy link

wenxd commented May 18, 2022

 function findLastCharacter(str, character) {
    let index = str.lastIndexOf(character)
    let res = str.slice(0, index) + str.slice(index+1)
    console.log(res);
  }
  findLastCharacter('sfafasf_u_ser_li_stnihao serach', 's')

@QQhuan
Copy link

QQhuan commented May 18, 2022

function delChar(str) { return str.replace(/\s$/, '') }

@xiaoqiangz
Copy link

// 考虑删除字符可能是多位字符的情况
let str1 = 'is xq my name is xq is xq '
function removeLastchar(str, del) {
let index = str.lastIndexOf(del)
if ( index > 0 ) {
// 第一种
return str.substring(0, index) + str.substring(index + del.length)
// 第二种 删除最后匹配项 然后再以删除的字符连接
let arr = str.split(del)
arr.splice(arr.length - 1, 1)
return arr.join(del)
}
}
console.log(removeLastchar(str1, 'is xq'))

@www-wanglong
Copy link

先行断言正则

function delLastChar(str, target) {
  let reg = new RegExp(`${target}(?=([^${target}]*)$)`)
 return str.replace(reg, '')
}

@web-ma-hub
Copy link

String.prototype.removeLastKeyword = function (keyword) {
  const string = this,
    lastIndex = string.lastIndexOf(keyword),
    strArr = this.split('')
  strArr.splice(lastIndex, 1)
  return strArr.join('')
}

@wyy-g
Copy link

wyy-g commented Sep 6, 2022

function delStr(str, delItem){
var index = str.lastIndexOf(delItem),
arr = str.split('');
arr.splice(index, delItem.length);
return arr.join('');
}

@luise2019
Copy link

function strDel(str,target){
let index = str.lastIndexOf(target);
let strNew = str.slice().split('');
strNew.splice(index,1);
return index===-1?str:strNew.join('');
}

@wl2282589971
Copy link

function trim(str, char) {
var index = str.lastIndexOf(char);
if (index == -1) {
return str;
} else {
return str.substring(0, index) + str.substring(index + 1);
}
}

@Hanies11
Copy link

Hanies11 commented Mar 9, 2023

let str = '12345678910';;
function deleteLastWord(str, word) {
let i = str.lastIndexOf(word);
return str.slice(0, i) + str.slice(i + 1, str.length + 1);
}
console.log(deleteLastWord(str, 1))

@xxj435
Copy link

xxj435 commented Sep 19, 2023

[js] 第3天 去除字符串中最后一个指定的字符

function strLastStr(str, lastStr) {
  let arr = str.split('');
  arr.splice(
    arr.reverse().findIndex((item) => item === lastStr),
    1
  );
  return arr.reverse().join('');
}
let res = strLastStr('dsafasdaw', 'a');
console.log(res);

@keenesun
Copy link

function replaceFn(str, tar) {
return str.replace(new RegExp(${tar}(?=[^${tar}]*$)), '')
}

(学习大佬后记录一下)

@13714273163
Copy link

13714273163 commented Oct 25, 2023 via email

@zjingwang
Copy link

const delLast = (str, chr) => {
let index = str.lastIndexOf(chr);
return str.substring(0, index) + str.substring(index + 1);

}

console.log(delLast('oncekiing', 'i'));

@zjingwang
Copy link

const delLast = (str, chr) => {
let index = str.lastIndexOf(chr);
return str.substring(0, index) + str.substring(index + 1);

}

console.log(delLast('oncekiing', 'i'));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests