Reputation: 942
Given the Javascript below how can I add a condition to the clause? I would like to add a "space" character after a separator only if a space does not already exist. The current code will result in double-spaces if a space character already exists in spacedText.
var separators = ['.', ',', '?', '!'];
for (var i = 0; i < separators.length; i++) {
var rg = new RegExp("\\" + separators[i], "g");
spacedText = spacedText.replace(rg, separators[i] + " ");
}
Upvotes: 0
Views: 100
Reputation: 531
I would suggest the following regexp to solve your problem:
"Test!Test! Test.Test 1,2,3,4 test".replace(/([!,.?])(?!\s)/g, "$1 ");
// "Test! Test! Test. Test 1, 2, 3, 4 test"
The regexp matches any character in the character class [!,.?]
not followed by a space (?!\s)
. The parenthesis around the character class means that the matched separator will be contained in the first backreference $1
, which is used in the replacement string. See this fiddle for working example.
Upvotes: 2
Reputation: 4625
Here is a working code :
var nonSpaced= 'Hello World!Which is your favorite number? 10,20,25,30 or other.answer fast.';
var spaced;
var patt = /\b([!\.,\?])+\b/g;
spaced = nonSpaced.replace(patt, '$1 ');
If you console.log
the value of spaced
, It will be : Hello World! Which is your favorite number? 10, 20, 25, 30 or other. answer fast.
Notice the number of space characters after the ?
sign , it is only one, and there is not extra space after last full-stop
.
Upvotes: 0
Reputation: 211
'. , ? ! .,?!foo'.replace(/([.,?!])(?! )/g, '$1 ');
//-> ". , ? ! . , ? ! foo"
Means replace every occurence of one of .,?! that is not followed by a space with itself and a space afterwards.
Upvotes: 2
Reputation: 36965
spacedText = spacedText.replace(/([\.,!\?])([^\s])/g,"$1 ")
This means: replace one of these characters ([\.,!\?]
) followed by a non-whitespace character ([^\s]
) with the match from first group and a space ("$1 "
).
Upvotes: 0
Reputation: 13615
You could do a replace of all above characters including a space. In that way you will capture any punctuation and it's trailing space and replace both by a single space.
"H1a!. A ?. ".replace(/[.,?! ]+/g, " ")
[.,?! ]
is a chararcter class. It will match either .
, ,
, ?
, !
or and + makes it match atleast once (but if possible multiple times).
Upvotes: 0