Reputation: 177
I have this function, which adds an extra spaces after comma.
function fixString1(inp){
var i, len, arr, outp, Rside, Lside, RsideIsNum, LsideIsNum;
arr = inp.split(",");
outp = "";
for(i=1, len=arr.length; i<len; i++){
Lside = arr[i-1];
Rside = arr[i];
LsideIsNum = /\d/.test(Lside.charAt(Lside.length-1));
RsideIsNum = /\d/.test(Rside.charAt(0));
outp += "," + ((LsideIsNum && RsideIsNum)?"":" ") + Rside;
}
return (arr[0] + outp).replace(/ {2,}/g, " ");
}
How can it modify to apply more than one character, I mean I want to apply this function besides comma to . ! ? :
chars too.
Anyone know how to solve?
Upvotes: 0
Views: 958
Reputation: 1734
Solution without regular expression.
jsFiddle
var str = " a a givi , asdad , saba a . sdada! hasdjahj ? asdas asd as luka , ";
function fixString(str) {
var temp = "",
count = 0;
str.split("").forEach(function (value, index, array) {
var next = array[index + 1],
x = value.charCodeAt(),
isChar = ((x >= 65 && x <= 90) || (x >= 97 && x <= 122));
if (value === " ") {
count++;
} else if (count > 0 && value !== " ") {
temp += ((next && next !== " ") || (temp.length > 0 && isChar) ? " " : "") + value;
count = 0;
} else {
temp += value;
}
});
return temp;
}
console.log(fixString(str));
Upvotes: 0
Reputation: 413976
I'm not sure I completely understand what you want to do, but I think you can do it much more concisely:
function fixString1( inp ) {
return inp.replace(/(\d)\s+([,!?:.])\s*(\d)/g, "$1$2$3")
.replace(/\s*([,!?:.])\s+/g, "$1 ");
}
The first regular expression looks for digits on either side of a special character, with intervening space on the left and possibly intervening space on the right. It replaces that with the two digits and the special character, and no spaces.
The second regular expression deals with all the other spaces around the special characters. It gets rid of all such spaces and makes sure there's one space following the special character.
Upvotes: 1
Reputation: 8310
Add one more parameter to the function declaration which indicates the character. If you want to run the function only once then you can provide a set of the characters in the split function e.g. inp.split(".,'")
Upvotes: 1