i am trying
To convert: 'any string separated with blankspaces' into
'any-string-separated-with-blankspaces'
i am tying with .replace(' ','-') but it would only replace first... why? how can i replace all?
http://jsfiddle.net/7ycg3/
You need a regular expression for that
.replace(/\s/g,'-')
\s will replace any kind of white-space character. If you're strictly after a "normal" whitespace use
/ /g
instead.
You need to use a regular expression as the first parameter, using the /g modifier to make it replace all occurrences:
var replaced = input.replace(/ /g,'-');
If you want to replace any whitespace character instead of a literal space, you need to use \s instead of in the regex; and if you want to replace any number of consecutive spaces with one hyphen, then add + after the or \s.
It's not stated particularly clearly in the MDN docs for String.replace, but String.replace only does one replacement, unless the g flag is included in it, using a regular expression rather than a string:
To perform a global search and replace, either include the g switch in the regular expression or if the first parameter is a string, include g in the flags parameter.
(But be aware that the flags parameter is non-standard, as they also note there.)
Thus, you want tag.replace(/ /g,'-').
http://jsfiddle.net/7ycg3/1/
Use regex with /g modifier
Use /\s/g inplace of ' ' in your question
Related
This seems a very simple question but I haven't been able to get this to work.
How do I convert the following string:
var origin_str = "abc/!/!"; // Original string
var modified_str = "abc!!"; // replaced string
I tried this:
console.log(origin_str.replace(/\\/,''));
This only removes the first occurrence of backslash. I want to replaceAll. I followed this instruction in SO: How to replace all occurrences of a string in JavaScript?
origin_str.replace(new RegExp('\\', 'g'), '');
This code throws me an error SyntaxError: Invalid regular expression: /\/: \ at end of pattern. What's the regex for removing backslash in javascript.
A quick basic overview of regular expressions in JavaScript
When using regular expressions you can define the expression on two ways.
Either directly in the function or variable by using /regular expression/
Or by using the regExp contructor: new RegExp('regular expression').
Please note the difference between the two ways of defining. In the first the search pattern is encapsuled by forward slashes, while in the second one the search pattern is passed as a string.
Remember that regular expressions is in fact a search language with it's own syntax. Some characters are used to define actions: /, \, ^, $, . (dot), |, ?, *, +, (, ), [, {, ', ". These characters are called metacharacters and need to be escaped if you want them to be part of the search pattern. If not they will be treated as an option or generate script errors. Escaping is done by using the backslash. E.g. \\ escapes the second backslash and the search pattern will now search for backslashes.
There are a multitude of options you can add to your search pattern.:
Examples
adding \d will make the pattern search for a numeric value between [0-9] and/or the underscore. Simple regular expressions are parsed from left to right.
/javascript/
Searches for the word javascript in a string.
/[a-z]/
When a pattern is put between square bracket the search pattern searches for a character matching any one of the values inside the square brackets. This will find d in 229302d34330
You can build a regular expression with multiple blocks.
/(java)|(emca)script/
Find javascript or emcascript in a string. The | is the or operator.
/a/ vs. /a+/
The first matches the first a in aaabbb, the second matches a repetition of a until another character is found. So the second matches: aaa.
The plus sign + means find a one or more times. You can also use * which means zero or more times.
/^\d+$/
We've seen the \d earlier and also the plus sign. This means find one or more numeric characters. The ^ (caret) and $ (dollar sign) are new. The ^ says start searching from the begin of the string, while the $ says until the end of the string. This expression will match: 574545485 but not d43849343, 549854fff or 4348d8788.
Flags
Flags are operators and are declared after the regular expression /regular expression/flags
JavaScript has three flags you can use:
g (global) Searches multiples times for the pattern.
i (ignore case) Ignores case in pattern.
m (multiline) treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string)
So a regular expression like this:
/d[0-9]+/ig
matches D094938 and D344783 in 98498D094938A37834D344783.
The i makes the search case-insensitive. Matching a D because of the d in the pattern. If D is followed by one or more numbers then the pattern is matched. The g flag commands the expression to look for the pattern globally or simply said: multiple times.
In your case #Qwerty provided the correct regex:
origin_str.replace(/\//g, "")
Where the search pattern is a single forward slash /. Escaped by the backslash to prevent script errors. The g flags commands the replace function to search for all occurrences of the forward slash in the string and replace them with an empty string "".
For a comprehensive tutorial and reference : http://www.regular-expressions.info/tutorial.html
Looking for this?
origin_str.replace(/\//g, "")
The syntax for replace is
.replace(/pattern/flags, replacement)
So in my case the pattern is \/ - an escaped slash
and g is global flag.
I would like to use .replace() function in JS to replace all occurencies of string "{5}".
I had no problems with letters in brackets but numbers just dont work if I call:
mystring.replace(/{\5}/g,'replaced')
nothing happens. Please can you help me with right syntax?
It looks like you have a problem with escaping. I'm pretty sure \5 is a backreference. You should instead be escaping the curly braces and not the number.
'Something {5} another thing'.replace(/\{5\}/g, 'replaced');
// -> Something replaced another thing
Additional Note: Just in case you're looking for a generalized string formatting solution, check out this SO question with some truly awesome answers.
Is there a special reason you are preceding the number with a backslash? If your intention is to match against the string "{5}", "{" and "}" are the special characters that should be escaped, not the character "5" itself!
According to MDN:
A backslash that precedes a non-special character indicates that the next character is
special and is not to be interpreted literally. For example, a 'b' without a preceding '\' generally matches lowercase 'b's wherever they occur. But a '\b' by itself doesn't match any character; it forms the special word boundary character.
The following code would work:
var str = "foo{5}bar{5}";
var newStr = str.replace(/\{5\}/g, "_test_");
console.log(newStr); // logs "foo_test_bar_test_"
Try this:
mystring.replace(/\{5\}/g,'replaced');
You need to escape the curly brackets\{ and \}.
DEMO
http://jsfiddle.net/tuga/Gnsq3/
Am i doing sth wrong or there is a problem with JS replace ?
<input type="text" id="a" value="(55) 55-55-55" />
document.write($("#a").val().replace(/()-/g,''));
prints (55) 555555
http://jsfiddle.net/Yb2yV/
how can i replace () and spaces too?
In a JavaScript regular expression, the ( and ) characters have special meaning. If you want to list them literally, put a backslash (\) in front of them.
If your goal is to get rid of all the (, ), -, and space characters, you could do it with a character class combined with an alternation (e.g., either-or) on \s, which stands for "whitespace":
document.write($("#a").val().replace(/[()\-]|\s/g,''));
(I didn't put backslashes in front of the () because you don't need to within a character class. I did put one in front of the - because within a character class, - has special meaning.)
Alternately, if you want to get rid of anything that isn't a digit, you can use \D:
document.write($("#a").val().replace(/\D/g,''));
\D means "not a digit" (note that it's a capital, \d in lower case is the opposite [any digit]).
More info on the MDN page on regular expressions.
You need to use a character class
/[-() ]/
Using "-" as the first character solves the ambiguity because a dash is normally used for ranges (e.g. [a-zA-Z0-9]).
document.write($("#a").val().replace(/[\s()-]/g,''));
That will remove all whitespace (\s), parens, and dashes
Use this
.replace(/\(|\)|-| /g,'')
You have to escape the parenthesis (i.e. \( instead of (). In your regexp, you want to list the four items: \(, \), '-' and (space) and as you want to replace any of them, not just a string of them four together, you have to use OR | between them.
May be very bad but a very basic approach would be,
document.write($("#a").val().replace(/(\()|(\))|-| |/g,''));
| means OR,
\ is used for escaping reserved symbols
You want to match any character in the set, so you should use square brackets to make a character set:
document.write($("#a").val().replace(/[()\- ]/g,''));
Normally, parentheses have a special meaning in regular expressions, so they were being ignored in your regex, leaving just the dash. Normally, to get literal parentheses, you need to escape them with \ (but in a square bracket block, as above, you don't).
The dash above is escaped because it has normally indicates range in a character set, e.g., [a-z].
The brackets indicate a capturing group in the regexp. You'd need to escape them (/\(\)-/) to match the sequence "()-". Yet I guess you want to use a character class, i.e. a expression that matches "(", ")" or "-"; for whitespaces include the \s shorthand:
value.replace(/[()-\s]/g, "");
You might want to read some documentation or tutorial.
I have a string "messages.get.342" that I want to convert to "messages/get/342". Unfortunately, when I call "messages.get.342".replace('.', '/'), I get "messages/get.342". What gives?
You need to use a global replace with regex like this.
"messages.get.342".replace(/\./g, '/');
Edit:
You can also do it like this; it is a little longer but can be less confusing.
var myString = "messages/get/342";
var regex = new RegExp(/\./, "g");
myString = mystring.replace(regex, myString);
You have the following three options available to you with the javascript regex object:
i - case insensitive matching
g - global matching
m - multiline matching
You can use the other two options in replace of the g (/i or "i") or in combination with the g (/gi or "gi").
Use Regular Expression
"messages.get.342".replace(/\./g, '/')
You need to use a regular expression with the global flag to replace ALL instances of the period:
document.write("messages.get.342".replace(/\./g, '/'));
Do it globally:
"messages.get.342".replace(/\./g, '/')
The \. is an escaped period, and the slashes around it indicate a pattern match. You have to escape a literal period if you're doing a pattern match. The g means global, i.e., match and replace all occurrences, not just the first.
Don't use replace for strings. "messages.get.342".split('.').join('/') is recommended.
I would like to select everything what's not [a-z0-9 ]
So if the string is:
Hello! How are you Mr. 007?
Then the result would be: !,?,.
Use a negated character class:
[^a-z0-9]
You will also need a case-insensitive modifier, or alternatively use this: [^a-zA-Z0-9].
Note that your expected result is incorrect: you missed the space character. If you want to also not match the space character you need to include it in the character class: [^a-zA-Z0-9 ].
With ^ at the beginning of a character class, you negate that class:
str.match(/[^a-z0-9 ]/gi)
You should also add space (or \s (which is space, tab,...)) and the modifier i to make the match case insensitive.
Read more about regular expressions in JavaScript and regular expressions in general.