I was trying to run this line of code and wondering why it is not working. Does anyone has an answer for this?
var string = "foo bar";
string = string.replace(" ", "");
alert(string.length);
why issit that the length of the string is not changed to 6 instead?
The function only replaces one instance of the string you search for.
To replace more, you can match with a regular expression:
string = string.replace(/\s+/g, '');
That strips all "whitespace" characters. The "\s" matches whitespace, the "+" means "one or more occurrences" of whitespace characters, and the trailing "g" means "do it to all matching sequences in the string".
Because you have more than one space in your string and the .replace is replacing one space, the first one encountered.
This works as expected, with only one space
var string = "foo bar";
string = string.replace(" ", "");
alert(string.length);
replace, when passed a string as the first parameter, only replaces the first occurrence of that string. To replace everything, you'd need a regular expression:
alert("foo bar".replace(/ /g, ""));
That's because only one space has been replaced. Per JavaScript 1.5 specification, String.replace() takes a regular expression as first parameter and the behavior for string parameters is undefined. Browsers later decided to treat strings similarly - but there is no way to specify g flag on a string, so only one replacement is done. This will do what you want:
string = string.replace(/ /g, '');
The version provided by Pointy (/\s+/g) might be more efficient however. And it will replace other types of whitespace (tabs, newlines) as well.
Related
I am trying to remove characters from a string so that it will match this RegEx: ^[-a-zA-Z0-9._:,]+$. For example:
const input = "test // hello". The expected output would be "test hello". I tried the following:
input.replace(/^[-a-zA-Z0-9._:,]+$/g, "")
But this does not seem to work
The example output "hello world" that you give does not match your regex, because the regex does not allow spaces. Assuming you want to keep spaces, use
input.replace(/[^-a-zA-Z0-9._:, ]/g, "")
The negation character ^ must be inside the [...]. The + is not needed, because /g already ensures that all matching characters are replaced (that is, removed).
If you also want to condense consecutive spaces into a single space (as implied by your example), use
input.replace(/[^-a-zA-Z0-9._:, ]/g, "").replace(/\s+/g, " ")
I like to use the following canonical approach:
var input = "test // hello";
var output = input.replace(/\s*[^-a-zA-Z0-9._:, ]+\s*/g, " ").trim()
console.log(output);
The logic here is to target all unwanted characters and their surrounding whitespace. We replace with just a single space. Then we do a trim at the end in case there might be an extra leading/trailing space.
I am stuck with creating regex such that if the word is preceded or ended by special character more than one regex on each side regex 'exec' method should throw null. Only if word is wrap with exactly one bracket on each side 'exec' method should give result Below is the regular expression I have come up with.
If the string is like "(test)" or then only regex.exec should have values for other combination such as "((test))" OR "((test)" OR "(test))" it should be null. Below code is not throwing null which it should. Please suggest.
var w1 = "\(test\)";
alert(new RegExp('(^|[' + '\(\)' + '])(' + w1 + ')(?=[' + '\(\)' + ']|$)', 'g').exec("this is ((test))"))
If you have a list of words and want to filter them, you can do the following.
string.split(' ').filter(function(word) {
return !(/^[!##$%^&*()]{2,}.+/).test(word) || !(/[!##$%^&*()]{2,}$).test(word)
});
The split() function splits a string at a space character and returns an array of words, which we can then filter.
To keep the valid words, we will test two regex expressions to see if the word starts or ends with 2 or more special characters respectively.
RegEx Breakdown
^ - Expression starts with the following
[] - A single character in the block
!##$%^&*() - These are the special characters I used. Replace them with the ones you want.
{2,} - Matches 2 or more of the preceeding characters
.+ - Matches 1 or more of any character
$ - Expression ends with the following
To use the exec function this way do this
!(/^[!##$%^&*()]{2,}.+/).exec(string) || !(/[!##$%^&*()]{2,}$).exec(string)
If I understand correctly, you are looking for any string which contains (test), anywhere in it, and exactly that, right?
In that case, what you probably need is the following:
var regExp = /.*[^)]\(test\)[^)].*/;
alert(regExp.exec("this is ((test))")); // → null
alert(regExp.exec("this is (test))" )); // → null
alert(regExp.exec("this is ((test)" )); // → null
alert(regExp.exec("this is (test) ...")); // → ["this is (test) ..."]
Explanation:
.* matches any character (except newline) between zero and unlimited times, as many times as possible.
[^)] match a single character but not the literal character )
This makes sure there's your test string in the given string, but it is only ever wrapped with one brace in every side!
You can use the following regex:
(^|[^(])(\(test\))(?!\))
See regex demo here, replace with $1<span style="new">$2</span>.
The regex features an alternation group (^|[^(]) that matches either start of string ^ or any character other than (. This alternation is a kind of a workaround since JS regex engine does not support look-behinds.
Then, (\(test\)) matches and captures (test). Note the round brackets are escaped. If they were not, they would be treated as a capturing group delimiters.
The (?!\)) is a look-ahead that makes sure there is no literal ) right after test). Look-aheads are supported fully by JS regex engine.
A JS snippet:
var re = /(^|[^(])(\(test\))(?!\))/gi;
var str = 'this is (test)\nthis is ((test))\nthis is ((test)\nthis is (test))\nthis is ((test\nthis is test))';
var subst = '$1<span style="new">$2</span>';
var result = str.replace(re, subst);
alert(result);
Attempting to get all alphanumeric chars after : symbol unless a space exists, in which case the space will be the terminating mark.
// the following should all return foo
text = 'a :foo bar';
text = 's:foo';
text = ':foo, test';
Tried this, but doesn't get stuff unless there's a space. I'll probably need a regex, but not sure how that would be constructed
var t = following.substring(following.lastIndexOf(":")+1,following.lastIndexOf(' '));
How about: /:([a-zA-Z0-9]+)/
':foo, test'.match(/:([a-zA-Z0-9]+)/)[1] //returns foo
's:foo'.match(/:([a-zA-Z0-9]+)/)[1] //returns foo
':foo, test'.match(/:([a-zA-Z0-9]+)/)[1] //returns foo
These RegEx uses 2 parts:
: finds the : followed by
[a-zA-Z0-9]+ any alphanumeric character
Note:
Since this Regulars Expressions matches the types of characters I specified there is not need in this case to "break on space" since it will only match the alphanumeric characters after : it will automatically exclude space, comma, etc. any other character included within the square brackets will make that character a possible match.
I'd suggest using regular expressions, such as (albeit untested):
var result = text.match(/:([a-zA-Z0-9]*)\s/)[1];
References:
javascript regular expressions.
String.match().
You could use regex like this
/:([\w]+)[\W]/g
I've got a string which contains q="AWORD" and I want to replace q="AWORD" with q="THEWORD". However, I don't know what AWORD is.. is it possible to combine a string and a regex to allow me to replace the parameter without knowing it's value? This is what I've got thus far...
globalparam.replace('q="/+./"', 'q="AWORD"');
What you have is just a string, not a regular expression. I think this is what you want:
globalparam.replace(/q=".+?"/, 'q="THEWORD"');
I don't know how you got the idea why you have to "combine" a string and a regular expression, but a regex does not need to exist of wildcards only. A regex is like a pattern that can contain wildcards but otherwise will try to match the exact characters given.
The expression shown above works as follows:
q=": Match the characters q, = and ".
.+?": Match any character (.) up to (and including) the next ". There must be at least one character (+) and the match is non-greedy (?), meaning it tries to match as few characters as possible. Otherwise, if you used .+", it would match all characters up to the last quotation mark in the string.
Learn more about regular expressions.
Felix's answer will give you the solution, but if you actually want to construct a regular expression using a string you can do it this way:
var fullstring = 'q="AWORD"';
var sampleStrToFind = 'AWORD';
var mat = 'q="'+sampleStrToFind+'"';
var re = new RegExp(mat);
var newstr = fullstring.replace(re,'q="THEWORD"');
alert(newstr);
mat = the regex you are building, combining strings or whatever is needed.
re = RegExp constructor, if you wanted to do global, case sensitivity, etc do it here.
The last line is string.replace(RegExp,replacement);
I just found this regex in JavaScript
var str=input.replace(/\0/g, "\\0");
Can you please explain me what does it mean? What is the meaning of /\0/g and \\0?
\0 is the null character.
/\0/g is a pattern that will match all instances of the null character.
"\\0" is a string that will be displayed as "\0", since the first backslash acts as an escape character for the second backslash.
So this line of code replaces all instances of the null character (which is normally unreadable, unless you use a hex viewer) in the string input and replaces them with the human-readable string "\0", then stores the result in the string str.
It replaces null characters (\0 - Unicode 0x0) in the string with a backslash (\)followed by a 0.
var s = "asd0asd\x00asd";
console.log(s);
s = s.replace(/\0/g, "\\0");
console.log(s);
And the output is:
asd0asd�asd
asd0asd\0asd