JavaScript text manipulation - javascript

Using JavaScript and I want to replace any text between #anytext# with some text. I want to make it generic so I am thinking to make use of regular expression. How do I do it?
Example:replace('#hello#','Hi')

Try this:
str.replace(/#[^#]+#/g, 'Hi')
This will remove any sequences of # … # globally with Hi.
Edit    Some explanation:
/…/ is the regular expression literal syntax in JavaScript
#[^#]+# describes any sequence of a literal #, followed by one or more (+ quantifier) characters that is not a # (negated charcater class [^#]), followed by a literal #
the g flag in /…/g allows global matches; otherwise only the first match would be replaced

You can use the regex function of jquery to accomplish that...
So find the #'s with a regular expression and afterwards use the replace function with the text you want.

This has nothing to do with jQuery, but just plain old javascript.
var regexp = new RegExp("#([^#]+)#");
text.replace(re, "replacement text");
But what do you mean by generic? How generic do you want to make it?
You can find more information about regular expressions on http://regexp.info including how to use in in Javascript

Related

How to combine regular expressions and template literals in JavaScript? [duplicate]

I am pretty new to Regexp and it seems that the \ is used for meta characters. My problem is I want to search this string exactly \"mediaType\":\"img\"
Now I also want to dynamically put a variable in for img. So I want it to be something like this
new RegExp(`\"mediaType\":\"${variable}\"`)
How do I write this to make it work?
Short answer:
function escapeRegEx(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var expression = new RegExp('\\\\"mediaType\\\\":\\\\"' + escapeRegEx(variable) + '\\\\"');
// or, using a template literal:
var expression = new RegExp(`\\\\"mediaType\\\\":\\\\"${escapeRegEx(variable)}\\\\"`);
Long answer:
Besides being used for meta characters, backslash in regular expressions can be used to escape characters that would otherwise have meaning (like *, $, parentheses, and \). So the way to match a backslash in a regular expression is to add another one as an escape character: \\.
Taking that into account, the regular expression you want to end up with is \\"mediaType\\":\\"img\\", and if you were using a regular expression literal that would be it. Unfortunately it gets a little more involved because you need to create an expression dynamically, you need to provide the expression as a string, which also needs the backslashes escaped. That adds a second layer of escaping, so you need to double up each of the \ characters again, and you end up with new RegExp('\\\\"mediaType\\\\":\\\\"img\\\\"').
Another complication is that you want the contents of variable to be matched literally, not interpreted as a regular expression. Unfortunately, there's no built-in way to automatically escape regular expressions in JavaScript, so you'll need to use one of the solutions in Is there a RegExp.escape function in Javascript?. I used a slightly modified version of the accepted answer that defines it as a standalone function instead of adding it to the RegExp object. The exact solution doesn't matter, as long as you escape the dynamic part.
You just want to use String.raw
const variable = 'text'
const regexp = new RegExp(String.raw `\"mediaType\":\"${variable}\"`)
console.log(regexp)

How to make \ a literal back slash using Regexp in JS

I am pretty new to Regexp and it seems that the \ is used for meta characters. My problem is I want to search this string exactly \"mediaType\":\"img\"
Now I also want to dynamically put a variable in for img. So I want it to be something like this
new RegExp(`\"mediaType\":\"${variable}\"`)
How do I write this to make it work?
Short answer:
function escapeRegEx(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var expression = new RegExp('\\\\"mediaType\\\\":\\\\"' + escapeRegEx(variable) + '\\\\"');
// or, using a template literal:
var expression = new RegExp(`\\\\"mediaType\\\\":\\\\"${escapeRegEx(variable)}\\\\"`);
Long answer:
Besides being used for meta characters, backslash in regular expressions can be used to escape characters that would otherwise have meaning (like *, $, parentheses, and \). So the way to match a backslash in a regular expression is to add another one as an escape character: \\.
Taking that into account, the regular expression you want to end up with is \\"mediaType\\":\\"img\\", and if you were using a regular expression literal that would be it. Unfortunately it gets a little more involved because you need to create an expression dynamically, you need to provide the expression as a string, which also needs the backslashes escaped. That adds a second layer of escaping, so you need to double up each of the \ characters again, and you end up with new RegExp('\\\\"mediaType\\\\":\\\\"img\\\\"').
Another complication is that you want the contents of variable to be matched literally, not interpreted as a regular expression. Unfortunately, there's no built-in way to automatically escape regular expressions in JavaScript, so you'll need to use one of the solutions in Is there a RegExp.escape function in Javascript?. I used a slightly modified version of the accepted answer that defines it as a standalone function instead of adding it to the RegExp object. The exact solution doesn't matter, as long as you escape the dynamic part.
You just want to use String.raw
const variable = 'text'
const regexp = new RegExp(String.raw `\"mediaType\":\"${variable}\"`)
console.log(regexp)

Create regular expression dynamically with regex chars

Say I want to match any of these files:
/foo/bar/baz/x
/foo/bar/baz/y/z
so I create a regex like so:
new RegExp('^/foo/bar/baz/.*')
however my question is - how do I tell the RegExp constructor to view . * and ^ as regular expression characters, not literal characters?
As this is node.js related, my solution would be to use quotemeta
https://github.com/substack/quotemeta
as if it was perl related my solution would be to use \Q \E ;-)
new RegExp('^/foo/bar/baz/.*')
...and
/^\/foo\/bar\/baz\/.*/
...are equivalent. Everything in the new RegExp string are treated as regular expression characters, not literal characters (luckily / does not need to be escaped).
If you do want to make something a literal character using the constructor syntax, make sure you use a double backslash since \ within a string literal has its own meaning. For example, if you want to capture a literal . character, this:
new RegExp('\.')
...won't work right because that is interpreted the same as '.', making the RegExp the same as /./. You'd need to do this instead:
new RegExp('\\.')

lookbehind in javascript?

I wanted to use regex to match and replace anything between my file name and closing parentheses.
I wrote a regex:
/(?<=imagecheck.php)[^)]*/
That works in php, but not in Javascript.
...How would I do in JS?
example:
input string example 1: url(127.0.0.1/imagecheck.php)
input string example 2: url(127.0.0.1/imagecheck.php?boost=9881732213826123918238)
outcome string example: url(127.0.0.1/imagecheck.php?reload=oh_yes_plx&boost=123810982346023984723948723023423)
Look-behind is not supported in Javascript. You can use capturing group to capture the text after "imagecheck.php" instead:
.match(/imagecheck.php([^)]*)/)
The result will be in index 1 of the returned array (if there is a match).
This is an example of removing whatever after "imagecheck.php"
.replace(/(imagecheck.php)[^)]*/, "$1")
Without look-behind in javascript, you can replace everything between your filename and the closing paren like this:
str = str.replace(/imagecheck.php\([^)]*\)/, "imagecheck.php(whatever)");
or, you can use capture groups and numbered references to avoid repeating the initial pattern:
str = str.replace(/(imagecheck.php)\([^)]*\)/, "$1(whatever)");
XRegExp doesn't support lookbehind directly. For that, you'd need to use the addon script previously linked to by #arxanas: http://blog.stevenlevithan.com/archives/javascript-regex-lookbehind. Also, XRegExp doesn't use forward-slash delimiters within its pattern strings.
Though Javascript doesn't natively support lookbehind in regular expressions, we could pull in XRegExp, a more powerful Javascript regex engine.
var pattern = XRegExp('/(?<=imagecheck.php)[^)]*/', 'g'); // g is the global flag
XRegExp.replace(input, pattern, replacement);

JavaScript split function - use of escape characters?

The following two examples do the same thing.
I was wondering why Option 1 is given in a code example I found and not Option 2?
What is the significance of the forward/backward slashes in '/\&/'
Option 1.
var pairs = qString.split(/\&/);
Option 2.
var pairs = qString.split('&');
split() is a function that can take a regex as well as a string parameter, the forward slash usage is something called a regex literal and it is not really passing a string but a regex object.
The following statements in javascript are the same.
var regex = /\&/; // Literal
var regex = new RegExp("\\&"); // Explicit
Option 1 uses a RegEx constant which is declared with surrounding forward slashed (/).
Option 2 uses a string.
See https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Regular_Expressions
The first example splits on a regular expression (constructed using the leaning-toothpick (/.../) syntax), while the second splits on a plain string.
Regular expressions are a powerful sub-language that allow complex string matching; in this case, the overhead of using one to split on a literal character (while probably negligible) is a little silly. It's like hiring a top-notch architect to build a wooden cube.
In the first example, the & character is mistakenly escaped (with the \), since it is not special in regular expressions. The regular expression engine gracefully handles that, however, and still treats it as a literal &.

Categories