I have a string from which I want to remove the last parentheses "(bob)". So far I use this code to return the value within these parentheses:
const str = "Hello my name is (john) (doe) (bob)";
const result = str.split('(').pop().split(')')[0];
console.log(result);
How would I be able to return the string without these last parentheses?
Source: How to remove the last word in a string using JavaScript
Possibly not the cleanest solution, but if you always want to remove the text behind last parentheses, it will work.
var str = "Hello my name is (john) (doe) (bob)";
var lastIndex = str.lastIndexOf("(");
str = str.substring(0, lastIndex);
console.log(str);
You can match the last occurrence of the parentthesis, and replace with capture group 1 that contains all that comea before it:
^(.*)\([^()]*\)
Regex demo
const str = 'Hello my name is (john) (doe) (bob)';
const lastIdxS = str.lastIndexOf('(');
console.log(str.slice(0, lastIdxS).trim());
Working in Javascript attempting to use a regular expression to capture data in a string.
My string appears as this starting with the left bracket
['ABC']['ABC.5']['ABC.5.1']
My goal is to get each piece of the regular expression as a chunk or in array.
I have reviewed and see that the match function might be a good choice.
var myString = "['ABC']['ABC.5']['ABC.5.1']";
myString.match(/\[/g]);
The output I see is only the [ for each element.
I would like the array to be like this for example
myString[0] = ['ABC']
myString[1] = ['ABC.5']
myString[2] = ['ABC.5.1']
What is the correct regular expression and or function to get the above-desired output?
If you just want to separate them, you can use a simple expression or better than that you can split them:
\[\'(.+?)'\]
const regex = /\[\'(.+?)'\]/gm;
const str = `['ABC']['ABC.5']['ABC.5.1']`;
const subst = `['$1']\n`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
DEMO
You can use this regex with split:
\[[^\]]+
Details
\[ - Matches [
[^\]]+ - Matches anything except ] one or more time
\] - Matches ]
let str = `['ABC']['ABC.5']['ABC.5.1']`
let op = str.split(/(\[[^\]]+\])/).filter(Boolean)
console.log(op)
How i can select RQR-1BN6Q360090-0001 (without quotes) using Regex in below -
<html><head><title>Object moved</title></head><body>
<h2>Object moved to here.</h2>
</body></html>
I tried this but it does not work
RptNum=([A-Za-z]+)$
You may use
/RptNum=([\w-]+)/
The pattern will match RptNum= and then capture 1 or more occurrences of word chars (letters, digits and _) or hyphens. See the regex demo and the regex graph:
Note that
/RptNum=([A-Z0-9-]+)/
might be a more restrictive pattern that should work, too. It does not match _ and lowercase letters.
In JS, use it with String#match() and grab the second array item upon a match:
var s = 'Object moved to here';
var m = s.match(/RptNum=([\w-]+)/);
if (m) {
console.log(m[1]);
}
Here, we can also use an expression that collects the new lines, such as:
[\s\S]*RptNum=(.+?)"[\s\S]*
[\w\W]*RptNum=(.+?)"[\w\W]*
[\d\D]*RptNum=(.+?)"[\d\D]*
and our desired output is saved in (.+?).
Test
const regex = /[\s\S]*RptNum=(.+?)"[\s\S]*/gm;
const str = `<html><head><title>Object moved</title></head><body>
<h2>Object moved to here.</h2>
</body></html>`;
const subst = `$1`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log(result);
Demo
RegEx
If this expression wasn't desired, it can be modified/changed in regex101.com.
RegEx Circuit
jex.im visualizes regular expressions:
const text = 'RptNum=RQR-1BN6Q360090-0001';
console.log(text.match(/RptNum=.*/).map(m => m.match(/RptNum=.*/)[0])[0].split('RptNum=')[1]);
I suppose that works
In javascript, how do I remove all special characters from the string except the semi-colon?
sample string: ABC/D A.b.c.;Qwerty
should return: ABCDAbc;Qwerty
You can use a regex that removes anything that isn't an alpha character or a semicolon like this /[^A-Za-z;]/g.
const str = "ABC/D A.b.c.;Qwerty";
const result = str.replace(/[^A-Za-z;]/g, "");
console.log(result);
var str = "ABC/D A.b.c.;Qwerty";
var result = str.replace(/[^A-Za-z;]/g, ""); // 21ABCDAbc;Qwerty
Live DEMO
$("#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;
}