Javascript regex - javascript

Currently I have a basic regex in javascript for replacing all whitespace in a string with a semi colon. Some of the characters within the string contain quotes. Ideally I would like to replace white space with a semi colon with the exception of whitespace within quotes.
var stringin = "\"james johnson\" joe \"wendy johnson\" tony";
var stringout = stringin.replace(/\s+/g, ":");
alert(stringout);
Thanks
Robin

Try something like this:
var stringin = "\"james johnson\" joe \"wendy johnson\" tony";
var stringout = stringin.replace(/\s+(?=([^"]*"[^"]*")*[^"]*$)/g, ":");
Note that it will break when there are escaped quotes in your string:
"ab \" cd" ef "gh ij"

in javascript, you can easily make fancy replacements with callbacks
var str = '"james \\"bigboy\\" johnson" joe "wendy johnson" tony';
alert(
str.replace(/("(\\.|[^"])*")|\s+/g, function($0, $1) { return $1 || ":" })
);

In this case regexes alone are not the simplest way to do it:
<html><body><script>
var stringin = "\"james \\\"johnson\" joe \"wendy johnson\" tony";
var splitstring = stringin.match (/"(?:\\"|[^"])+"|\S+/g);
var stringout = splitstring.join (":");
alert(stringout);
</script></body></html>
Here the complicated regex containing \\" is for the case that you want escaped quotes like \" within the quoted strings to also work. If you don't need that, the fourth line can be simplified to
var splitstring = stringin.match (/"[^"]+"|\S+/g);

Related

Access Matched Text at RegExp

I want to escape : and white space at my regex. I tried that:
var re = new RegExp(':| ', 'g');
var result = $(this).attr("id").replace(re, '\\${1}');
However it doesn't work. This is what I want to do:
Jack Kerouac => Jack\\ Kerouac
Albert:Camus => Albert\\:Camus
How can I do that?
There is no need for braces use $& to get the match within the string and use \\\\ for double slash since \\ produces single slash(one slash is for escaping).
.replace(re, '\\$&');
var str = `Jack Kerouac
Albert:Camus`;
var re = new RegExp(':| ', 'g');
console.log(str.replace(re, '\\$&'));
you can use pattern directly instead of instantiating with RegExp object.
also \\ -> produce one \ (escape), add \\\\
var re = /\:|\s/g;
var val1="fname lname";
var val2="fname:lname";
console.log(val1.replace(re,'\\\\$&'));
console.log(val2.replace(re,'\\\\$&'));
This captures more than one space character:
s.replace( \(:| )+\g, '\\\\' )
You can play with more options here - https://regex101.com/r/WW67KE/1

How do I delete all characters starting from a specific text on a string

The best way to explain this is by example. I'm using jQuery to do this.
Example I have a string
var str = "1.) Ben"
how can I dynamically omit the character 1.) including the space such that str === "Ben"
str can be dynamic such that order can increment from ones, tens, to hundreds.
E.G.
var str = "52.) Ken Bush"
or
var str = "182.) Hailey Quen"
Expected output
str === "Ken Bush"
or
str === "Hailey Quen"
Example
var str = "182.) Hailey Quen"
var test = str.split(') ');
test = test[1];
//output "Hailey Quen"
You can use regex replacement to get what you want.
var str = "182.) Hailey"
var newStr = str.replace(/^\d+\.\)\s*/, '')
// Hailey
var s = "1456.) Hard Spocker".replace(/^\d+\.\)\s*/, '')
// Hard Spocker
^ makes sure that the pattern is matched at the start of the string only
\d+ will match one or more digits.
\. will match the . with escaping
) is a symbol so we need to escape it using \ as \)
\s* will match one or more spaces.
You can learn about these symbols here.
Try using .substring() and .indexOf() as shown :-
var str = "182.) Hailey Quen"
alert(str.substring(str.indexOf(' ')))
DEMO
OR use .split() as shown :-
var str = "182.) Hailey Quen"
alert($.trim(str.split(')')[1]))
DEMO
You can do it regular expression,
var str = "52.) Ken".replace(/\d+\.\)\s/g,"");
console.log(str); //Ken
DEMO
If you have zero or more than zero spaces after the ) symbol then you can use *,
var str = "52.) Ken".replace(/\d+\.\)\s*/g,"");
console.log(str); //Ken
Dismantling regex used,
/ states regex left border
\d d states normal character d, if we want to make it match
numbers then we have to escape it with \
+ It states that one or more number should be there.
\. Again . is a metacharacter to match any valid character, so
escape it.
\) Parenthesis is also a metacharacter to close a group, escape
it.
\s* 12.) can be followed by zero or more spaces.
/ states regex right boundary.
g global flag, which used to do a search recursively.
You can do it like this
var testURL = "182.) Hailey Quen";
var output = testURL.substring(testURL.lastIndexOf(")") + 1).trim();
console.log(output);
*trim function will help to remove extra space if any.Hope it will help

Javascript - Detect certain characters within a string and replace content between those characters

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.

Simple regex replace brackets

Is there an easy way to make this string:
(53.5595313, 10.009969899999987)
to this String
[53.5595313, 10.009969899999987]
with JavaScript or jQuery?
I tried with multiple replace which seems not so elegant to me
str = str.replace("(","[").replace(")","]")
Well, since you asked for regex:
var input = "(53.5595313, 10.009969899999987)";
var output = input.replace(/^\((.+)\)$/,"[$1]");
// OR to replace all parens, not just one at start and end:
var output = input.replace(/\(/g,"[").replace(/\)/g,"]");
...but that's kind of complicated. You could just use .slice():
var output = "[" + input.slice(1,-1) + "]";
For what it's worth, to replace both ( and ) use:
str = "(boob)";
str = str.replace(/[\(\)]/g, ""); // yields "boob"
regex character meanings:
[ = start a group of characters to look for
\( = escape the opening parenthesis
\) = escape the closing parenthesis
] = close the group
g = global (replace all that are found)
Edit
Actually, the two escape characters are redundant and eslint will warn you with:
Unnecessary escape character: ) no-useless-escape
The correct form is:
str.replace(/[()]/g, "")
var s ="(53.5595313, 10.009969899999987)";
s.replace(/\((.*)\)/, "[$1]")
This Javascript should do the job as well as the answer by 'nnnnnn' above
stringObject = stringObject.replace('(', '[').replace(')', ']')
If you need not only one bracket pair but several bracket replacements, you can use this regex:
var input = "(53.5, 10.009) more stuff then (12) then (abc, 234)";
var output = input.replace(/\((.+?)\)/g, "[$1]");
console.log(output);
[53.5, 10.009] more stuff then [12] then [abc, 234]

Remove ALL white spaces from text

$("#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;
}

Categories