Forum Moderators: open

Message Too Old, No Replies

Strip all non-alphabetical chars via JS?

         

lkalisky

9:42 am on Jun 5, 2008 (gmt 0)

10+ Year Member



Hi,

I would like to take this string:

 [Sports & Fitness] > General

and make it into:

 Sports+Fitness+General

Can someone help with doing this via JS?

Thanks!

mehh

4:19 pm on Jun 5, 2008 (gmt 0)

10+ Year Member



var str="[Sports & Fitness] > General"
str.replace(/\W+/g,"+");

birdbrain

6:18 pm on Jun 5, 2008 (gmt 0)



Hi there lkalisky,

note that \W will not remove numerals or underscores.
If you want them removed and do not want more than one "+" between words or a "+" at the beginning or end of the string, then try it like this...


<script type="text/javascript">

var strings=[
'[Sports & Fitness] > General',
'<Webmaster>World{Forums} Rock@~',
'*&^Bird087__987brain(0#@"'
];

for(c=0;c<strings.length;c++) {

strings[c]=strings[c].replace(/\W[red]¦[/red]\d[red]¦[/red]\_/g,'+').replace(/\+{2,}/g,'+').replace(/^(\+)[red]¦[/red](\+)$/g,'');

alert(strings[c]);

}

</script>

Note:- The l symbol above the backward slash on the keyboard is changed to ¦ by Webmaster World Forums. :(
I do not know the reason for this idiosyncrasy. ;)
So make sure that the three used in the script-(highlighted in red)- are replaced with the correct symbol.

birdbrain

Dabrowski

8:10 pm on Jun 5, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I would use a regex, but much simpler.

Note, this would work in Perl, I do use Regex in JS but some things are different, so please test this and let me know.

var str = "[Sports & Fitness] > General"; 
var newstr = str.replace( /[^a-zA-Z]/, " "); // Replace any non letters with a space
var newerstr = newstr.replace( /\s+/, "+"); // Replace one or more spaces, with just a +