Jump to content

Javascript -- Remove white space characters


Guest notadummy
 Share

Recommended Posts

Guest notadummy

My task: Omit words from a chapter. Although the words are omitted, they are replaced with white space characters. What Javascript code do I use to remove the 'replacement' white space characters? Example: words to omit = 'for', 'and', 'the', 'to'A man needs something to relieve the stress and pain for now. Should read:A man needs something relieve stress pain now. My code is as follows: CHAPTER_WORDS_TO_OMIT = Array('for', 'and', 'the', 'to');if (mytitle.match(/^<[1234567890]+>/) != null) { for (i = 0; i < CHAPTER_WORDS_TO_OMIT.length; i++) { eval('mytitle = mytitle.replace(/ ' + CHAPTER_WORDS_TO_OMIT + '/ig, " ")'); } } else {

Link to comment
Share on other sites

Funky code.Anyway, the space is being created by the replace method. See those double quotation marks near the end of the parentheses? They contain an empty space. So that's what's replacing the search term. Delete the space from the expression and you should be okay. I mean THIS:'/ig, " "should look like this:'/ig, ""

Link to comment
Share on other sites

You'll also have a double space any time one of those words is removed from the middle of a sentence.

...relieve the stress...becomes...relieve  stress...

To counter that you'll also need to check for whitespace characters in your regex.I'm not 100% sure if this is right so you'll need to test it:/\s? ' + CHAPTER_WORDS_TO_OMIT[i ] + '\s?/ig[b]Note[/b] remove the space after the i in CHAPTER_WORDS_TO_OMIT[i ] I had to add a space otherwise BBCode would format my postThe \s? tells it to look for one or zero whitespace characters. [i]If[/i] (and that's a big if :) ) this is right, I think you'll have to use a space as the replace character otherwise words will get smashed into one. (In other words, if my regex is correct, ignore what DD said above)

Link to comment
Share on other sites

I'm having success with this:

var myWord, re;var CHAPTER_WORDS_TO_OMIT = ['for', 'and', 'the', 'to']; // this shortcut is called JSONvar len = CHAPTER_WORDS_TO_OMIT.length;if (myTitle.match(/^<[0-9]+>/)) {   for (i = 0; i < len; i++) {	  myWord = CHAPTER_WORDS_TO_OMIT[i];	  re = new RegExp( "(\\s+"  +  myWord  +  ")|("  +  myWord  +  "\\s+)", "ig" );	  myTitle = myTitle.replace(re, "");   }}

Building a regex on the fly makes nasty looking code. Use of the RegExp function avoids the sinister eval() statement. I assume your titles look something like this:<1> Jimmy and the Bird Go Flying

Edited by Deirdre's Dad
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...