Nice programing

문자열에서 마지막 문자 교체

nicepro 2020. 11. 22. 20:31
반응형

문자열에서 마지막 문자 교체


jQuery에서 주어진 문자열에서 '_'(밑줄)의 마지막 발생을 대체하는 쉬운 방법이 있습니까?


jQuery는 필요하지 않고 정규 표현식 만 있으면됩니다.

마지막 밑줄이 제거됩니다.

var str = 'a_b_c';
str = str.replace(/_([^_]*)$/,'$1'); //a_bc

그러면 변수의 내용으로 대체됩니다 replacement.

var str = 'a_b_c', replacement = '!';
str = str.replace(/_([^_]*)$/,replacement+'$1'); //a_b!c

교체하려는 문자가 문자열에 존재한다고 가정하면 jQuery 또는 정규식이 필요하지 않습니다.

문자열의 마지막 문자 바꾸기

str = str.substring(0,str.length-2)+otherchar

문자열의 마지막 밑줄 바꾸기

var pos = str.lastIndexOf('_');
str = str.substring(0,pos) + otherchar + str.substring(pos+1)

또는 다른 답변의 정규식 중 하나를 사용하십시오.

var str1 = "Replace the full stop with a questionmark."
var str2 = "Replace last _ with another char other than the underscore _ near the end"

// Replace last char in a string

console.log(
  str1.substring(0,str1.length-2)+"?"
)  
// alternative syntax
console.log(
  str1.slice(0,-1)+"?"
)

// Replace last underscore in a string 

var pos = str2.lastIndexOf('_'), otherchar = "|";
console.log(
  str2.substring(0,pos) + otherchar + str2.substring(pos+1)
)
// alternative syntax

console.log(
  str2.slice(0,pos) + otherchar + str2.slice(pos+1)
)


이건 어때?

function replaceLast(x, y, z){
  var a = x.split("");
  a[x.lastIndexOf(y)] = z;
  return a.join("");
}

replaceLast("Hello world!", "l", "x"); // Hello worxd!

문자열을 뒤집고, 문자를 바꾸고, 문자열을 뒤집습니다.

다음은 자바 스크립트에서 문자열 반전에 대한 게시물입니다. 자바 스크립트에서 문자열을 어떻게 반전합니까?


간단하게

var someString = "a_b_c";
var newCharacter = "+";

var newString = someString.substring(0, someString.lastIndexOf('_')) + newCharacter + someString.substring(someString.lastIndexOf('_')+1);

This is very similar to mplungjan's answer, but can be a bit easier (especially if you need to do other string manipulation right after and want to keep it as an array) Anyway, I just thought I'd put it out there in case someone prefers it.

var str = 'a_b_c';
str = str.split(''); //['a','_','b','_','c']
str.splice(str.lastIndexOf('_'),1,'-'); //['a','_','b','-','c']
str = str.join(''); //'a_b-c'

The '_' can be swapped out with the char you want to replace

And the '-' can be replaced with the char or string you want to replace it with


Another super clear way of doing this could be as follows:

let modifiedString = originalString
   .split('').reverse().join('')
   .replace('_', '')
   .split('').reverse().join('')

You can use this code

var str="test_String_ABC";
var strReplacedWith=" and ";
var currentIndex = str.lastIndexOf("_");
str = str.substring(0, currentIndex) + strReplacedWith + str.substring(currentIndex + 1, str.length);

alert(str);


    // Define variables
    let haystack = 'I do not want to replace this, but this'
    let needle = 'this'
    let replacement = 'hey it works :)'
    
    // Reverse it
    haystack = Array.from(haystack).reverse().join('')
    needle = Array.from(needle).reverse().join('')
    replacement = Array.from(replacement).reverse().join('')
    
    // Make the replacement
    haystack = haystack.replace(needle, replacement)
    
    // Reverse it back
    let results = Array.from(haystack).reverse().join('')
    console.log(results)
    // 'I do not want to replace this, but hey it works :)'


This is a recursive way that removes multiple occurrences of "endchar":

function TrimEnd(str, endchar) {
  while (str.endsWith(endchar) && str !== "" && endchar !== "") {
    str = str.slice(0, -1);
  }
  return str;
}

var res = TrimEnd("Look at me. I'm a string without dots at the end...", ".");
console.log(res)

참고URL : https://stackoverflow.com/questions/5497318/replace-last-occurrence-of-character-in-string

반응형