Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change spaces to underscore and make string case insensitive?

I have following question. In my app there is a listview. I get itemname from listview and transfer it to the webview as a string. How to ignore case of this string and change spaces to underscores?

For example: String itemname = "First Topic". I transfer it to the next activity and want to ignore case and change space to underscore (I want to get first_topic in result). I get "itemname" in webviewactivity and want to do what I've described for following code:

String filename = bundle.getString("itemname") + ".html"; 

Please, help.

like image 594
Sabre Avatar asked Feb 27 '12 07:02

Sabre


People also ask

How do you replace a space underscore in a string?

Use the String. replaceAll method to replace all spaces with underscores in a JavaScript string, e.g. string. replaceAll(' ', '_') . The replaceAll method returns a new string with all whitespace characters replaced by underscores.

How do you get rid of spaces in a string?

Use the String. replace() method to remove all whitespace from a string, e.g. str. replace(/\s/g, '') . The replace() method will remove all whitespace characters by replacing them with an empty string.


2 Answers

use replaceAll and toLowerCase methods like this:

myString = myString.replaceAll(" ", "_").toLowerCase()

like image 77
shift66 Avatar answered Sep 25 '22 15:09

shift66


This works for me:

itemname = itemname.replaceAll("\\s+", "_").toLowerCase(); 

replaceAll("\\s+", "_") replaces consecutive whitespaces with a single underscore.

"first topic".replaceAll("\\s+", "_") -> first_topic

"first topic".replaceAll(" ", "_") -> first__topic

like image 32
Chris Ociepa Avatar answered Sep 23 '22 15:09

Chris Ociepa