Given a string like:
\"The dog has a long tail, and it is RED!\"
What kind of jQuery or JavaScript magic can be used to keep spaces to only o
var string = "The dog has a long tail, and it is RED!";
var replaced = string.replace(/ +/g, " ");
Or if you also want to replace tabs:
var replaced = string.replace(/\s+/g, " ");
is replace is not used, string = string.split(/\W+/);
This script removes any white space (multiple spaces, tabs, returns, etc) between words and trims:
// Trims & replaces any wihtespacing to single space between words
String.prototype.clearExtraSpace = function(){
var _trimLeft = /^\s+/,
_trimRight = /\s+$/,
_multiple = /\s+/g;
return this.replace(_trimLeft, '').replace(_trimRight, '').replace(_multiple, ' ');
};
For more control you can use the replace callback to handle the value.
value = "tags:HUNT tags:HUNT tags:HUNT tags:HUNT"
value.replace(new RegExp(`(?:\\s+)(?:tags)`, 'g'), $1 => ` ${$1.trim()}`)
//"tags:HUNT tags:HUNT tags:HUNT tags:HUNT"
I know we have to use regex, but during an interview, I was asked to do WITHOUT USING REGEX.
@slightlytyler helped me in coming with the below approach.
const testStr = "I LOVE STACKOVERFLOW LOL";
const removeSpaces = str => {
const chars = str.split('');
const nextChars = chars.reduce(
(acc, c) => {
if (c === ' ') {
const lastChar = acc[acc.length - 1];
if (lastChar === ' ') {
return acc;
}
}
return [...acc, c];
},
[],
);
const nextStr = nextChars.join('');
return nextStr
};
console.log(removeSpaces(testStr));