I want to know the regular expression for inserting characters BEFORE the matched characters from the Regular Expression. For example:
var string = "HelloYouHowAreYou"
var regEx = /[A-Z\s]/g //to identify capital letters, but want to insert a dash before them
string = string.replace(regEx,"-")
console.log(string)
How can I accompish this?
You could use a positive lookahead, which looks for the specified characters, but not insert it into the match group and prevent the first character to get a dash at the beginning of the string.
/(?!^)(?=[A-Z])/g
var string = "HelloYouHowAreYou",
regEx = /(?!^)(?=[A-Z])/g;
string = string.replace(regEx, "-");
console.log(string);
You just need to use $& backreference in the replacement pattern to refer to the whole match:
var string = "HelloYouHowAreYou"
var regEx = /[A-Z\s]/g;
string = string.replace(regEx,"-$&")
console.log(string)
If you want to avoid matching the uppercase ASCII letter at the beginning of the string, add a (?!^) at the beginning:
var string = "HelloYouHowAreYou"
var regEx = /(?!^)[A-Z\s]/g;
string = string.replace(regEx,"-$&")
console.log(string)
Note that \s matches whitespace. If you want to only match uppercase ASCII letters, use
/[A-Z]/g
Wiktor Stribiżew has a great answer already, but you can also pass a function to the replace method if you want to do additional manipulation of the string.
var string = "HelloYouHowAreYou"
var regEx = /[A-Z\s]/g //to identify capital letters, but want to insert a dash before them
function replacer(match) {
return ('-') + (match);
}
string = string.replace(regEx,replacer)
console.log(string)
Related
I'm trying to detect an occurrence of a string within string. But the code below always returns "null". Obviously something went wrong, but since I'm a newbie, I can't spot it. I'm expecting that the code returns "true" instead of "null"
var searchStr = 'width';
var strRegExPattern = '/'+searchStr+'\b/';
"32:width: 900px;".match(new RegExp(strRegExPattern,'g'));
Please don't put '/' when you pass string in RegExp option
Following would be fine
var strRegExPattern = '\\b'+searchStr+'\\b';
"32:width: 900px;".match(new RegExp(strRegExPattern,'g'));
You're mixing up the two ways of creating regexes in JavaScript. If you use a regex literal, / is the regex delimiter, the g modifier immediately follows the closing delimiter, and \b is the escape sequence for a word boundary:
var regex = /width\b/g;
If you create it in the form of a string literal for the RegExp constructor, you leave off the regex delimiters, you pass modifiers in the form of a second string argument, and you have to double the backslashes in regex escape sequences:
var regex = new RegExp('width\\b', 'g');
The way you're doing it, the \b is being converted to a backspace character before it reaches the regex compiler; you have to escape the backslash to get it past JavaScript's string-literal escape-sequence processing. Or use a regex literal.
The right tool for this job is not regex, but String.indexOf:
var str = '32:width: 900px;',
search = 'width',
isInString = !(str.indexOf(search) == -1);
// isInString will be a boolean. true in this case
Documentation: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/String/indexOf
Notice that '\\b' is a single slash in a string followed by the letter 'b', '\b' is the escape code \b, which doesn't exist, and collapses to 'b'.
Also consider escaping metacharacters in the string if you intend them to only match their literal values.
var string = 'width';
var quotemeta_string = string.replace(/[^$\[\]+*?.(){}\\|]/g, '\\$1'); // escape meta chars
var pattern = quotemeta_string + '\\b';
var re = new RegExp(pattern);
var bool_match = re.test(input); // just test whether matches
var list_matches = input.match(re); // get captured results
You can use back tick symbol to make your string dynamic "`".
var colName = 'Col1';
var result = strTest.match(`xxxxxxx${colName}`);
by injecting ${colName} in to the text, it can be editable dynamically.
I am using a replace function to escape some characters (both newline and backslash) from a string.
Here is my code:
var str = strElement.replace(/\\/\n/g, "");
I am trying to use regex, so that I can add more special characters if needed. Is this a valid regex or can someone tell me what am I doing wrong here?
You're ending the regex early with an unescaped forward slash. You also want to use a set to match individual characters. Additionally you might want to add "\r" (carriage return) in as well as "\n" (new line).
This should work:
var str = strElement.replace(/[\\\n\r]/g, "");
This is not a valid regex as the slash is a delimiter and ends the regex. What you probably wanted is the pipe (|), which is an alternation:
var str = strElement.replace(/\\|\n/g, "");
In case you need to extend it in the future it may be helpful to use a character class to improve readability:
var str = strElement.replace(/[\\\nabcx]/g, "");
A character class matches a single character from it's body.
This should work. The regular expression replaces both the newline characters and the backslashes in escaped html text:
var str = strElement.replace(/\\n|\\r|\\/g, '');
I have a filename that can have multiple dots in it and could end with any extension:
tro.lo.lo.lo.lo.lo.png
I need to use a regex to replace the last occurrence of the dot with another string like #2x and then the dot again (very much like a retina image filename) i.e.:
tro.lo.png -> tro.lo#2x.png
Here's what I have so far but it won't match anything...
str = "http://example.com/image.png";
str.replace(/.([^.]*)$/, " #2x.");
any suggestions?
You do not need a regex for this. String.lastIndexOf will do.
var str = 'tro.lo.lo.lo.lo.lo.zip';
var i = str.lastIndexOf('.');
if (i != -1) {
str = str.substr(0, i) + "#2x" + str.substr(i);
}
See it in action.
Update: A regex solution, just for the fun of it:
str = str.replace(/\.(?=[^.]*$)/, "#2x.");
Matches a literal dot and then asserts ((?=) is positive lookahead) that no other character up to the end of the string is a dot. The replacement should include the one dot that was matched, unless you want to remove it.
Just use special replacement pattern $1 in the replacement string:
console.log("tro.lo.lo.lo.lo.lo.png".replace(/\.([^.]+)$/, "#2x.$1"));
// "tro.lo.lo.lo.lo.lo#2x.png"
You can use the expression \.([^.]*?):
str.replace(/\.([^.]*?)$/, "#2x.$1");
You need to reference the $1 subgroup to copy the portion back into the resulting string.
working demo http://jsfiddle.net/AbDyh/1/
code
var str = 'tro.lo.lo.lo.lo.lo.zip',
replacement = '#2x.';
str = str.replace(/.([^.]*)$/, replacement + '$1');
$('.test').html(str);
alert(str);
To match all characters from the beginning of the string until (and including) the last occurence of a character use:
^.*\.(?=[^.]*$) To match the last occurrence of the "." character
^.*_(?=[^.]*$) To match the last occurrence of the "_" character
Use \. to match a dot. The character . matches any character.
Therefore str.replace(/\.([^\.]*)$/, ' #2x.').
You could simply do like this,
> "tro.lo.lo.lo.lo.lo.zip".replace(/^(.*)\./, "$1#2x");
'tro.lo.lo.lo.lo.lo#2xzip'
Why not simply split the string and add said suffix to the second to last entry:
var arr = 'tro.lo.lo.lo.lo.lo.zip'.split('.');
arr[arr.length-2] += '#2x';
var newString = arr.join('.');
'tro.lo.lo.lo.lo.lo.png'.replace(/([^\.]+).+(\.[^.]+)/, "$1.#x2$2")
I'm trying to detect an occurrence of a string within string. But the code below always returns "null". Obviously something went wrong, but since I'm a newbie, I can't spot it. I'm expecting that the code returns "true" instead of "null"
var searchStr = 'width';
var strRegExPattern = '/'+searchStr+'\b/';
"32:width: 900px;".match(new RegExp(strRegExPattern,'g'));
Please don't put '/' when you pass string in RegExp option
Following would be fine
var strRegExPattern = '\\b'+searchStr+'\\b';
"32:width: 900px;".match(new RegExp(strRegExPattern,'g'));
You're mixing up the two ways of creating regexes in JavaScript. If you use a regex literal, / is the regex delimiter, the g modifier immediately follows the closing delimiter, and \b is the escape sequence for a word boundary:
var regex = /width\b/g;
If you create it in the form of a string literal for the RegExp constructor, you leave off the regex delimiters, you pass modifiers in the form of a second string argument, and you have to double the backslashes in regex escape sequences:
var regex = new RegExp('width\\b', 'g');
The way you're doing it, the \b is being converted to a backspace character before it reaches the regex compiler; you have to escape the backslash to get it past JavaScript's string-literal escape-sequence processing. Or use a regex literal.
The right tool for this job is not regex, but String.indexOf:
var str = '32:width: 900px;',
search = 'width',
isInString = !(str.indexOf(search) == -1);
// isInString will be a boolean. true in this case
Documentation: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/String/indexOf
Notice that '\\b' is a single slash in a string followed by the letter 'b', '\b' is the escape code \b, which doesn't exist, and collapses to 'b'.
Also consider escaping metacharacters in the string if you intend them to only match their literal values.
var string = 'width';
var quotemeta_string = string.replace(/[^$\[\]+*?.(){}\\|]/g, '\\$1'); // escape meta chars
var pattern = quotemeta_string + '\\b';
var re = new RegExp(pattern);
var bool_match = re.test(input); // just test whether matches
var list_matches = input.match(re); // get captured results
You can use back tick symbol to make your string dynamic "`".
var colName = 'Col1';
var result = strTest.match(`xxxxxxx${colName}`);
by injecting ${colName} in to the text, it can be editable dynamically.
The sample string:
this!is.an?example
I want to match: this is an example.
I tried this:
<script type="text/javascript">
var string="this!is.an?example";
var pattern=/^\W/g;
alert(string.match(pattern));
</script>
Try this:
var words = "this!is.an?example".split(/[!.?,;:'"-]/);
This will create an string array containing each word.
If you want to turn it into a single string with the words separated by spaces, you can call words.join(" ").
EDIT: You could also split on \W (str.split(/\W/)), but that may match more characters than you want.
I can't understand why you want to explicitly match, but if your goal is to strip all punctuation, this would work:
var words = "this!is.an?example".split(/\W/);
words = words.join(' ');
\W will match any character except letters, digits and underscore.
If you want to split also on underscores, use this:
var words = "this!is.an?example_with|underscore".split(/\W|_/);
If you just want to match:
(\w|\.|!|\?)+
If you want to replace all punctuation with a whitespace, you could do this:
var str = str.replaceAll([^A-Za-z0-9]," ");
This replaces all non letters, numerals with a space.
/^\W/g means match a string where the first character is not a letter or number
and the string "this!is.an?example" obviously does not begin with a non-letter or non-number.
Remember that ^ means the whole string start with, not what you want to match start with. And also remember that capital \W is everything that is not matched by small \w. With that reminder what you probably want is:
var string="this!is.an?example";
var pattern=/(\w+)/g; // parens for capturing
alert(string.match(pattern).join(' ')); // if you don't join,
// some browsers will simply
// print "[object Object]"
// or something like it