Replace specific character only when within a boundary - javascript

Replace specific character only when within a boundary.
For example replace html entity only when enclosed inside single quotes.
Input:
<i>Hello</i> '<i>How are you</i>'
Output:
<i>Hello</i> '<i>How are you</i>'

You can use replace with a callback:
var s = "<i>Hello</i> '<i>How are you</i>'";
var r = s.replace(/('[^']+')/g, function($0, $1) {
return $1.replace(/</g, '<').replace(/>/g, '>'); });
//=> <i>Hello</i> '<i>How are you</i&gt';

You'll need to use several regular expressions, first capture the text within single quotes, and then replace all occurrences of your character.
var input = "<i>Hello</i> '<i>How are you</i>'";
var quoted = input.match(/'.*'/)[0];
var output = quoted.replace("<", "<").replace(">", ">");
// output == "<i>Hello</i> '<i>How are you</i>'"

Related

Replace multiple characters in a string using regex

I want to replace multiple occurrences of multiple characters in a string.Let's say I have a string which contains spaces and / characters. How can I replace both with _?
I know how to replace a single character with the replace() method as below:
var s = 'some+multi+word+string'.replace(/\+/g, ' ');
How can I update this to replace multiple characters?
To capture multiple consecutive characters use the + operator in the Regex. Also note that to capture spaces and slashes you can specify them in a character set, for example [\s\/]. Try this:
var s = 'some multi///word/string'.replace(/[\s\/]+/g, '_');
console.log(s);
Define your characters inside a list []
const r = "abc def/ //g h".replace(/[ \/]/g, "_");
console.log(r) // "abc_def____g_h"
To replace multiple, use the + quantifier (one or more occurrences)
const r = "abc def/ //g h".replace(/[ \/]+/g, "_");
console.log(r) // "abc_def_g_h"
To replace the exact sequence " /" (Space+ForwardSlash) with "_"
const r = "abc /def /g /h".replace(/ \/+/g, "_");
console.log(r) // "abc_def_g_h"

Is it possible to do a double replace?

If double replace is it possible to do?
var string = [link="<iframe"qwe"></iframe>"]
var output = string.replace(/[link="([^"]+)"]/g, '$1.replace(/"([^"]+)"/g, "'")');
what i want output:
[link="<iframe'qwe'></iframe>"]
You can use a function as the replacement in replace(). It can then do its own replace on the capture group.
var string = '[link="<iframe"qwe"></iframe>"]';
var output = string.replace(/link="([^\]]+)"]/g, (match, group1) =>
'link="' + group1.replace(/"/g, "'") + '"]');
console.log(output);
Note also that I had to correct your regexp. ([^"]+) should be ([^\]]+) so that it can match a string containing double quotes -- you need to capture that so you can replace the double quotes.
And in the second replacement, you want to match ", not [^"]+

Remove string between two variables

I have a string which has some data with a few special characters, Need to remove the data between the desired special char in JavaScript.
The special char would be obtained in a variable.
var desiredChar = "~0~";
And Imagine this to be the Input string:
~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~
So I'm supposed to remove the text in bold.
The desired output is supposed to be-
~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~
I've tried using "Replace" and "Regex", but as the desired character is being passed in a variable and keeps changing I'm facing difficulties.
You can create your own regex based on whatever the bounding character(s) are that contain the text you want removed, and then replace any text that matches that regex with a blank string "".
The JS below should work for your use case (and it should work for multiple occurrences as well):
var originalText = "~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~";
var desiredChar = "~0~";
var customRegex = new RegExp(desiredChar + ".*?" + desiredChar, "gi");
var processedText = originalText.replace(customRegex, "");
console.log(processedText);
You can build your regex from the constructor with a string input.
var desiredChar = "~0~";
// use the g flag in your regex if you want to remove all substrings between desiredChar
var myRegex = new Regex(desiredChar + ".*" + desiredChar, 'ig');
var testString = "~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~";
testString = testString.replace(myRegex, "");
Given input string you can use .indexOf(), .lastIndexOf() and .slice().
Note, OR character | passed to RegExp constructor should be escaped to avoid RegExp created by passing string interpreting | character as OR | within resulting RegExp passed to .replace().
var desiredChar = "~0~";
var str = "~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~";
var not = str.slice(str.indexOf(desiredChar), str.lastIndexOf(desiredChar) + desiredChar.length);
// escape OR `|`
var res = str.replace(new RegExp(not.replace(/[|]/g, "\\|")), "");
console.log(res)
You can use the RegExp object:
var regexstring = "whatever";
var regexp = new RegExp(regexstring, "gi");
var str = "whateverTest";
var str2 = str.replace(regexp, "other");
document.write(str2);
Then you can construct regexstring in any way you want.
You can read more about it at http://www.regular-expressions.info/javascript.html

Remove whitespace after a particular symbol

I've got a string which has the > symbol multiple times. After every > symbol there is a line break. How can I remove whitespaces after every > symbol in the string?
This is what I tried for spaces. But I need to remove whitespaces only after > symbol.
str.replace(/\s/g, '');
String:
<Apple is red>
<Grapes - Purple>
<Strawberries are Red>
If you are trying to remove newline characters you can use RegExp /(>)(\n)/g to replace second capture group (\n) with replacement empty string ""
var str = `<Apple is red>
<Grapes - Purple>
<Strawberries are Red>`;
console.log(`str:${str}`);
var res = str.replace(/(>)(\n)/g, "$1");
console.log(`res:${res}`);
Try this:
str.replace(/>\s/g, '>')
Demo:
console.log(`<Apple is red>
<Grapes - Purple>
<Strawberries are Red>`.replace(/>\s/g, '>'))
Use the following approach:
var str = 'some> text > the end>',
replaced = str.replace(/(\>)\s+/g, "$1");
console.log(replaced);
You must use /m flag on your regex pattern
You must use $1 capture group symbol on your replacement text
var text = '<Apple is red>\r\n<Grapes - Purple>\r\n<Strawberries are Red>';
var regex = /(>)\s*[\n]/gm;
var strippedText = text.replace(regex,'$1');

How to execute a capturing group multiple times?

I have this string:
var str = "some text start:anything can be here some other text";
And here is expected result:
//=> some text start:anythingcanbehere some other text
In other word, I'm trying to remove all white spaces between a specific range of such a string.
Also Here is what I have tried:
(start:)(?:(\S+)(\s+))(.*)(?= some)
It works as well, but I should execute it several times to achieve expected result .. How can I use \1+ in my regex to run it several times?
You can't do what you want with a simple regexp replace, because a capture group can only capture one string -- there's no looping. Javascript allows you to provide a function as the replacement, and it can perform more complex operations on the captured strings.
var str = "some text start:anything can be here some other text";
var newstr = str.replace(/(start:)(.*)(?= some)/, function(match, g1, g2) {
return g1 + g2.replace(/ /g, '');
});
alert(newstr);
Using replace with a callback:
var repl = str.replace(/(start:.*?)(?= some\b)/, function(_, $1) {
return $1.replace(/\s+/g, ''); });
//=> some text start:anythingcanbehere some other text

Categories

Resources