[英]Remove character from string using javascript
i have comma separated string like 我有逗号分隔的字符串
var test = 1,3,4,5,6,
i want to remove particular character from this string using java script 我想使用Java脚本从此字符串中删除特定字符
can anyone suggests me? 有人可以建议我吗?
JavaScript strings provide you with replace method which takes as a parameter a string of which the first instance is replaced or a RegEx
, which if being global, replaces all instances. JavaScript字符串为您提供了replace方法,该方法将替换第一个实例的字符串或RegEx
用作参数,如果是全局的,则替换所有实例。
Example: 例:
var str = 'aba';
str.replace('a', ''); // results in 'ba'
str.replace(/a/g, ''); // results in 'b'
If you alert str - you will get back the same original string cause strings are immutable. 如果您警告str-您将获得相同的原始字符串,因为字符串是不可变的。 You will need to assign it back to the string : 您将需要将其分配回字符串:
str = str.replace('a', '');
Use replace
and if you want to remove multiple occurrence of the character use 使用replace
,如果要删除多次出现的字符,请使用
replace like this 像这样替换
var test = "1,3,4,5,6,";
var newTest = test.replace(/,/g, '-');
here newTest will became "1-3-4-5-6-"
在这里,newTest将变为"1-3-4-5-6-"
you can make use of JavaScript replace()
Method 您可以使用JavaScript replace()
方法
var str="Visit Microsoft!";
var n=str.replace("Microsoft","My Blog");
var test = '1,3,4,5,6';
//to remove character
document.write(test.replace(/,/g, ''));
//to remove number
function removeNum(string, val){
var arr = string.split(',');
for(var i in arr){
if(arr[i] == val){
arr.splice(i, 1);
i--;
}
}
return arr.join(',');
}
var str = removeNum(test,3);
document.write(str); // output 1,4,5,6
You can also 你也可以
var test1 = test.split(','); var test1 = test.split(',');
delete test1[2]; 删除test1 [2];
var test2 = test1.toString(); var test2 = test1.toString();
Have fun :) 玩得开心 :)
you can split the string by comma into an array and then remove the particular element [character or number or even string] from that array. 您可以用逗号将字符串分割成一个数组,然后从该数组中删除特定的元素[字符,数字或什至字符串]。 once the element(s) removed, you can join the elements in the array into a string again 删除元素后,您可以再次将数组中的元素连接到字符串中
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
You can use this function 您可以使用此功能
function removeComma(inputNumber,char='') {
return inputNumber.replace(/,/g, char);
}
Update 更新资料
function removeComma(inputNumber) {
inputNumber = inputNumber.toString();
return Number(inputNumber.replace(/,/g, ''));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.