1

i have this string "Gem. Buitentemperatuur (etmaal)"

And i would like to replace all whitespaces, capitals and special chars so that i end up with

"gem_buitentemperatuur_etmaal"

5 Answers 5

1

Try this

var yourStr = "Gem. Buitentemperatuur (etmaal)";
var newStr = yourStr.replace(/\s+/g, "_").replace(/\W+/g, "").toLowerCase();
//gem_buitentemperatuur_etmaal

.replace() is used to manipulate your string, a simple regular expression is passed to this and the value you want to replace it with

First we replace the Whitespace.

/  <- start the regex
\s <- match whitespace character
+  <- matches one or more times
/  <- end the regex.

And we replace this with your underscore .replace(/\s+/g, "_")

then find and match all non word characters.

/  <- start the regex
\W <- match all non word characters (everything but a-z, A-Z, 0-9 and _)
+  <- matches one or more times
/  <- end the regex

This part looks like this .replace(/\W+/g, "")

the g after the closing / stands for global to look all along the string and not just for the first match.

Here's a fiddle

Sign up to request clarification or add additional context in comments.

Comments

1
"Gem. Buitentemperatuur (etmaal)".toLowerCase().replace(/[^a-z]+(?!$)/g, "_").replace(/^[^a-z]|[^a-z]$/, "");

Comments

1

try this

function escapeRegExp(str) {
   return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

function replaceAll(find, replace, str) {
   return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}

Comments

1

You can use:

s="Gem. Buitentemperatuur (etmaal)";
s.toLowerCase().replace(/ +/g, '_').replace(/\W+/g, '');
//=> "gem_buitentemperatuur_etmaal"

Comments

1

Use this:

[^\w]+    

And .replace() with _.

Working example: http://regex101.com/r/nN9pX7

var str = "Gem. Buitentemperatuur (etmaal)";
str.replace(/\W+/g, "_").toLowerCase().replace(/(^_|_$)/, "");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.