Replacing spaces with underscores in JavaScript?
Try .replace(/ /g,"_");
Edit: or .split(' ').join('_')
if you have an aversion to REs
Edit: John Resig said:
If you're searching and replacing
through a string with a static search
and a static replace it's faster to
perform the action with
.split("match").join("replace") -
which seems counter-intuitive but it
manages to work that way in most
modern browsers. (There are changes
going in place to grossly improve the
performance of .replace(/match/g,
"replace") in the next version of
Firefox - so the previous statement
won't be the case for long.)
Replace initial spaces with underscores in Javascript
I want to replace each of the leading spaces with an underscore
To do that with just one replace
call within the current spec,* you'd need the function call version of replace
to do that, creating a string of underscores as long as the matched sequence of spaces:
y = x.replace(/^ +/, function(m) {
return "_".repeat(m.length);
});
or with an ES2015+ arrow function:
y = x.replace(/^ +/, m => "_".repeat(m.length));
Live Example:
const x = " four spaces";const y = x.replace(/^ +/, m => "_".repeat(m.length));console.log(y);
How to replace all spaces in a string
var result = replaceSpace.replace(/ /g, ";");
Here, / /g
is a regex (regular expression). The flag g
means global. It causes all matches to be replaced.
How to replace underscores with spaces?
You can replace all underscores in a string with a space like so:
str.replace(/_/g, ' ');
So just do that before the content is put in. If you need to perform the replacement afterwards, loop using each
:
$('.name').each(function () {
this.textContent = this.textContent.replace(/_/g, ' ');
});
Replace spaces with dashes and make all letters lower-case
Just use the String replace
and toLowerCase
methods, for example:
var str = "Sonic Free Games";
str = str.replace(/\s+/g, '-').toLowerCase();
console.log(str); // "sonic-free-games"
Notice the g
flag on the RegExp
, it will make the replacement globally within the string, if it's not used, only the first occurrence will be replaced, and also, that RegExp
will match one or more white-space characters.
Replace commas, full stops, hyphens, and spaces with underscore
You need to escape the -
character, because it's used to specify a range of characters like 0-9
or a-z
.
console.log('Helo,._cool '.replace(/[,.\- ]/g, "_"));
How can I regex replace all spaces in matched text with underscore? (Javascript)
Use a function in the replace()
method. That function can perform a nested replacement on that capture group.
let str = `enum class test{ something1, // this is a comment something2, // something else something3,};`;
let new_str = str.replace(/\,.*\/\/\s*(.*)/g, (match0, match1) => ' | ' + match1.replace(/ /g, '_'));console.log(new_str);
change spaces entered in input field to underscore in real time
You may listen to the input
event and then replace the spaces with underscores in the listener. This way, you don't need to have a timeout.
$("#inputId").on('input', function(key) { var value = $(this).val(); $(this).val(value.replace(/ /g, '_'));})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><input type="text" id="inputId">
Related Topics
Generate HTML Table from 2D JavaScript Array
Math Random Number Without Repeating a Previous Number
How to Stop Babel from Transpiling 'This' to 'Undefined' (And Inserting "Use Strict")
Access-Control-Allow-Origin Denied Spotify API
How to Animate Scrolltop with Jquery
How to Use Command Line Arguments in Angularjs Protractor
Chrome Extension: Port Error: Could Not Establish Connection. Receiving End Does Not Exist
Testing If a Checkbox Is Checked with Jquery
How to Convert JSON Object to JavaScript Array
Javascript: Uncaught Typeerror: Cannot Call Method 'Addeventlistener' of Null
Deep Copy in Es6 Using the Spread Syntax
Three.Js:2Xmeshes Using Same Vector as Position
What Are the Semantics of Different Rxjs Subjects