program tip

문자열에서 마지막 쉼표 제거

radiobox 2020. 7. 24. 20:23
반응형

문자열에서 마지막 쉼표 제거


JavaScript를 사용하여 마지막 쉼표를 제거 할 수 있지만 쉼표가 마지막 문자이거나 쉼표 뒤에 공백 만있는 경우에만 어떻게해야합니까? 이것은 내 코드입니다. 나는 일하는 바이올린을 얻었다 . 그러나 버그가 있습니다.

var str = 'This, is a test.'; 
alert( removeLastComma(str) ); // should remain unchanged

var str = 'This, is a test,'; 
alert( removeLastComma(str) ); // should remove the last comma

var str = 'This is a test,          '; 
alert( removeLastComma(str) ); // should remove the last comma

function removeLastComma(strng){        
    var n=strng.lastIndexOf(",");
    var a=strng.substring(0,n) 
    return a;
}

마지막 쉼표와 그 뒤에 공백이 제거됩니다.

str = str.replace(/,\s*$/, "");

정규 표현식을 사용합니다.

  • /마크 시작과 정규 표현식의 끝

  • ,쉼표 일치

  • \s수단 공백 문자 (공백, 탭 등)과 *수단 0 이상

  • $끝에 문자열의 끝을 의미


slice () 메소드를 사용하여 문자열에서 마지막 쉼표를 제거 할 수 있습니다. 아래 예제를 찾으십시오 .

var strVal = $.trim($('.txtValue').val());
var lastChar = strVal.slice(-1);
if (lastChar == ',') {
    strVal = strVal.slice(0, -1);
}

여기에 예가 있습니다

function myFunction() {
	var strVal = $.trim($('.txtValue').text());
	var lastChar = strVal.slice(-1);
	if (lastChar == ',') { // check last character is string
		strVal = strVal.slice(0, -1); // trim last character
		$("#demo").text(strVal);
	}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<p class="txtValue">Striing with Commma,</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>


function removeLastComma(str) {
   return str.replace(/,(\s+)?$/, '');   
}

여기서 멀다

var sentence="I got,. commas, here,";
var pattern=/,/g;
var currentIndex;
while (pattern.test(sentence)==true)  {    
  currentIndex=pattern.lastIndex;
 }
if(currentIndex==sentence.trim().length)
alert(sentence.substring(0,currentIndex-1));
else
 alert(sentence);

The problem is that you remove the last comma in the string, not the comma if it's the last thing in the string. So you should put an if to check if the last char is ',' and change it if it is.

EDIT: Is it really that confusing?

'This, is a random string'

Your code finds the last comma from the string and stores only 'This, ' because, the last comma is after 'This' not at the end of the string.


The greatly upvoted answer removes not only the final comma, but also any spaces that follow. But removing those following spaces was not what was part of the original problem. So:

let str = 'abc,def,ghi, ';
let str2 = str.replace(/,(?=\s*$)/, '');
alert("'" + str2 + "'");
'abc,def,ghi '

https://jsfiddle.net/dc8moa3k/


you can remove last comma:

var sentence = "I got,. commas, here,";
sentence = sentence.replace(/(.+),$/, '$1');
console.log(sentence);

Remove last comma. Working example

function truncateText() {
  var str= document.getElementById('input').value;
  str = str.replace(/,\s*$/, "");
  console.log(str);
}
<input id="input" value="address line one,"/>
<button onclick="truncateText()">Truncate</button>


A late answer but probably should help someone.

For removing any last char from a string.

var str = "one, two, three,";
var str2 = str.substring(0, str.length - 1);
alert(str);
alert(str2);

참고URL : https://stackoverflow.com/questions/17720264/remove-last-comma-from-a-string

반응형