I am trying to replace # and space from a string if it has these two characters.
This is for markdown previewer.
var t = document.getElementById("textbox");
var h1 = (t.value === "/#\s/") ? t.value.replace(/^[#\s]/, "") : t.value;
console.log(h1);
How do I solve this problem?
If you want to categorically strip all pounds signs and spaces, then you should be using:
//var t = document.getElementById("textbox");
var t = "Hello#World Goodbye";
t = t.replace(/[# ]/g, "");
console.log(t);
Note the character for space, is just space, not \s, which means all whitespace (including things like newlines and tabs).
Try
let h1 = textbox.value.replace(/#| /g, '');
console.log(h1);
<input id="textbox" value="H a v e Nice#Day###">
Related
I need help in javascript where the word entered can be replaced as:
Input - A.. BC
Output - A-BC
the code that i have tried is:
var text = 'A.. BC';
new_text = text.replace(' ', '-') && text.replace('.','-');
console.log(new_text);
This is not working as it is giving me the output as:
A-. BC
I'd use a regular expression instead. Use a character set to match one or more dots, commas, or spaces, then replace with a dash:
const change = str => str.replace(/[., ]+/g, '-');
console.log(change('A.. BC'));
Use a charater set
var text = 'A.. BC';
new_text = text.replace(/[., ]+/g, '-');
console.log(new_text);
you can try replacing all non-alphabetical characters with a hyphen with regex:
const a = 'A.. BC';
const b = 'A ..BC';
// Find all non-word characters regex
const r = /[\W]+/g;
const hyphen = '-';
void console.log(a.replace(r, hyphen));
void console.log(b.replace(r, hyphen));
// A-BC
// A-BC
Below is my code.
var str = 'test//123_456';
var new_str = str .replace(/\//g, '').replace(/_/g, '');
console.log(new_str);
It will print test123456 on the screen.
My question is how to do it in same regular express? not replace string twice.
Thanks.
Use character class in the regex to match any character in the collection. Although use repetition (+, 1 or more) for replacing // in a single match.
var new_str = str .replace(/[/_]+/g, '');
var str = 'test//123_456';
var new_str = str.replace(/[/_]+/g, '');
console.log(new_str);
FYI : Inside the character class, there is no need to escape the forward slash(in case of Javascript RegExp).
Use the regex to match the list of character by using regex character class.
var str = "test//123_456";
var nstr = str.replace(/[\/_]/g, '');
I would like to remove white spaces and hyphens from a given string.
var string = "john-doe alejnadro";
var new_string = string.replace(/-\s/g,"")
Doesn't work, but this next line works for me:
var new_string = string.replace(/-/g,"").replace(/ /g, "")
How do I do it in one go ?
Use alternation:
var new_string = string.replace(/-|\s/g,"");
a|b will match either a or b, so this matches both hyphens and whitespace.
Example:
> "hyphen-containing string".replace(/-|\s/g,"")
'hyphencontainingstring'
You have to use:
var new_string = string.replace(/[-\s]/g,"")
/-\s/ means hyphen followed by white space.
Use This for Hyphens
var str="185-51-671";
var newStr = str.replace(/-/g, "");
White Space
var Actuly = newStr.trim();
I'm kind of a newby with Javascript, and regex in general and would appreciate all help I can receive!
Consider the following command: [Doesn't matter where it's executed]
/Ban Tom {Breaking The Rules} 5
What I need to do is detect the string between {}, replace the spaces with underscores there(_) and remove the curly brackets around the new string.
Example of outcome:
/Ban Tom Breaking_The_Rules 5
Thanks,
Tom.
You don't really need a RegEx as this can be achieved by just normal javascript:
<script type="text/javascript">
var str = "/Ban Tom {Breaking The Rules} 5";
var oldStr = str.substring(str.indexOf("{"), (str.indexOf("}") + 1));
var newStr = oldStr.replace(/ /g, "_").replace("{", "").replace("}", "");
alert(str.replace(oldStr, newStr));
</script>
use string.toCharArray() and parse through the array for matching { and spaces to replace them.
var str = '/Ban Tom {Breaking The Rules} 5';
var patt=new RegExp('{[^}].*}',i);
var res = patt.exec(str);
//include res check here.....
var newStr = res[0].replace(/ /g, '_');
newStr = newStr.replace(/[{}]/g, '');
str = newStr.replace(res[0], newStr);
// The Message:
var foo = "/Ban Tom {Breaking The Rules} 5";
// Replace Whitespace in braces:
foo = foo.replace(/\s+(?=[^\{\}]*\})/g, "_");
//Replace braces with nothing:
foo.replace(/[\{\}]/g,""):
First regex explanation:
\s+ // Match whitespace
(?= // If followed by:
[^\{\}]* // Any number of characters except braces
\} // The closing brace
) // End of the lookahed
This post provided most of the information, I just adapted it to javascript.
$("#topNav" + $("#breadCrumb2nd").text().replace(" ", "")).addClass("current");
This is a snippet from my code. I want to add a class to an ID after getting another ID's text property. The problem with this, is the ID holding the text I need, contains gaps between the letters.
I would like the white spaces removed. I have tried TRIM()and REPLACE() but this only partially works. The REPLACE() only removes the 1st space.
You have to tell replace() to repeat the regex:
.replace(/ /g,'')
The g character makes it a "global" match, meaning it repeats the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.
If you want to match all whitespace, and not just the literal space character, use \s instead:
.replace(/\s/g,'')
You can also use .replaceAll if you're using a sufficiently recent version of JavaScript, but there's not really any reason to for your specific use case, since catching all whitespace requires a regex, and when using a regex with .replaceAll, it must be global, so you just end up with extra typing:
.replaceAll(/\s/g,'')
.replace(/\s+/, "")
Will replace the first whitespace only, this includes spaces, tabs and new lines.
To replace all whitespace in the string you need to use global mode
.replace(/\s/g, "")
Now you can use "replaceAll":
console.log(' a b c d e f g '.replaceAll(' ',''));
will print:
abcdefg
But not working in every possible browser:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
Regex for remove white space
\s+
var str = "Visit Microsoft!";
var res = str.replace(/\s+/g, "");
console.log(res);
or
[ ]+
var str = "Visit Microsoft!";
var res = str.replace(/[ ]+/g, "");
console.log(res);
Remove all white space at begin of string
^[ ]+
var str = " Visit Microsoft!";
var res = str.replace(/^[ ]+/g, "");
console.log(res);
remove all white space at end of string
[ ]+$
var str = "Visit Microsoft! ";
var res = str.replace(/[ ]+$/g, "");
console.log(res);
var mystring="fg gg";
console.log(mystring.replaceAll(' ',''))
** 100% working
use replace(/ +/g,'_'):
let text = "I love you"
text = text.replace( / +/g, '_') // replace with underscore ('_')
console.log(text) // I_love_you
Using String.prototype.replace with regex, as mentioned in the other answers, is certainly the best solution.
But, just for fun, you can also remove all whitespaces from a text by using String.prototype.split and String.prototype.join:
const text = ' a b c d e f g ';
const newText = text.split(/\s/).join('');
console.log(newText); // prints abcdefg
I don't understand why we need to use regex here when we can simply use replaceAll
let result = string.replaceAll(' ', '')
result will store string without spaces
let str = 'a big fat hen clock mouse '
console.log(str.split(' ').join(''))
// abigfathenclockmouse
Use string.replace(/\s/g,'')
This will solve the problem.
Happy Coding !!!
simple solution could be : just replace white space ask key value
val = val.replace(' ', '')
Use replace(/\s+/g,''),
for example:
const stripped = ' My String With A Lot Whitespace '.replace(/\s+/g, '')// 'MyStringWithALotWhitespace'
Well, we can also use that [^A-Za-z] with g flag for removing all the spaces in text. Where negated or complemente or ^. Show to the every character or range of character which is inside the brackets. And the about g is indicating that we search globally.
let str = "D S# D2m4a r k 23";
// We are only allowed the character in that range A-Za-z
str = str.replace(/[^A-Za-z]/g,""); // output:- DSDmark
console.log(str)
javascript - Remove ALL white spaces from text - Stack Overflow
Using .replace(/\s+/g,'') works fine;
Example:
this.slug = removeAccent(this.slug).replace(/\s+/g,'');
function RemoveAllSpaces(ToRemove)
{
let str = new String(ToRemove);
while(str.includes(" "))
{
str = str.replace(" ", "");
}
return str;
}