Javascript replacing text in string with other text - javascript

I am creating a linking system that needs to be cross platform, i.e work on a webapp as well as a mobile app.
The API returns a string that looks like this,
Go to {P}Project Name{/P}
OR
Go to {F}File Name{/F}
I need to search for an occurance of {P} and {F} and replace this with a on my webapp, and then search for {/P} or {/F} and replace that with
I am trying to do this with javascript but I am coming unstuck, here is what I have so far,
var body = this.get('body');
if(body.match( \({P}|{F}/) {
}
after this I come unstuck my regex knowledge is not what it should be, can some point me in the correct direction?

One way:
str = str.replace(/({[PF]}(.*?){\/[PF]})/g, '$2');
For Go to Project Name

Consider:
str = "Go to {P}Project Name{/P}"
str = str.replace(/({P}|{F})/, '<a href="">');
str = str.replace(/({\/P}|{\/F})/, '</a>');
alert(str);
See it in action
Shorter updated solution:
str = "Go to {P}Project Name{/P}"
str = str.replace(/({P}|{F})(.*?)({\/P}|{\/F})/g, '$2');
alert(str);
See Updated DEMO

I'd recommend looking at the JS regex tuturials either at Javascript Kit or at w3schools.
In your case, you're failing to open the regex with a slash (/), and there's also the fact that brackets ({}) have a special significance on a regular expression, so you'll have to escape it.
Your regex should be something like /\{[PF]\}(.*?)\{\/[PF]\}/.

You can use indexOf (pure JS) to check whether you can find {P} or {F} in your string. Then replace them.
var str = "Go to {P}Project Name{/P}"; //this is just an example, it may contains F
if (str.indexOf("{P}" != -1} {//will return -1 if it doesn't have
str = str.replace("{P}", "<a href="">");
str = str.replace("{/P}", "</a>");
} else {
str = str.replace("{F}", "<a href="">");
str = str.replace("{/F}", "</a>");
}

Related

Escaping Regex single-quote creates extra backslashes on repl.it

I am trying to write a prototype method that first needs to escape backslashes \ when the input contains a plain single quote '. (I am aware that extending the prototype is bad practice in almost any other circumstance - this is merely a practice problem I'm trying to solve.)
I've checked out the Regex wiki and tried implementing the solutions to several regex-related questions, but I still seem to be missing something. In all of my attempts, I've been unable to 'escape the escape' as shown below:
String.prototype.escapeQuote = function () {
const regex = /\'/g;
const str = `${this}`;
const subst = `\\'`;
const result = str.replace(regex, subst);
return result;
};
var str = "this method doesn't work...";
str.escapeQuote();
When I run this code, I expect the output to be:
this method doesn\'t work...
But the output I get when I run it on repl.it is:
'this method doesn\\\'t work...'
binding subst to \' or just ' doesn't work either (perhaps it goes without saying) - either way the result is:
'this method doesn\'t work...'
I am pretty fuzzy on Regex, but trying to improve, so I'd appreciate any help you could provide - and, for that matter, any relevant answers I might have missed.
That's a rendering artifact of how the REPL you are using represents a string when it displays a string as the result of evaluating your code.
Note that it also wraps it in ' to indicate it is a string.
There are no slashes in the string itself, which you can see in this example:
String.prototype.escapeQuote = function() {
const regex = /(')/g;
const subst = `\\'`;
const result = this.replace(regex, subst);
return result;
};
const str = `doesn't this sound awesome`;
alert(str + "\n\n" + str.escapeQuote());
You should use the unescaped string inside a regular expression.
Like this:
String.prototype.escapeQuote = function(){
return this.replace(/'/g, '\\\'');
}
console.log("Try it, it's easier!".escapeQuote());
If you don't like that nasty '\\\'', you can use "\\'" instead.
Hope this works for you.
If you want to escape both single and double quotes, you can use this:
String.prototype.escapeQuotes = function(){
return this.replace(/["']/g, '\\$&');
}
console.log("Try it, it's easier!".escapeQuotes());

Get a substring from a string for a regular expression in JavaScript

I have a string of the following form:
data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'>Avatar data
It can be in different languages, but in any case I need to get a string which is between the characters ' '
That is, in the example above, I need to get the following string:
view-7631b26ea80b1b601c313b15cc4e2ab03faedf30
Can I do this using the method string.replace(regexp, str) ?
I've highlighted the desired line using the following regular expression:
/'\b(.*)\b'/gm
Now, using the method string.replace I need to delete everything except that...
Got any suggestions?
Use match method.
var data = "data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'>Avatar data";
data = data.match(/'\b(.*)\b'/gm)
You have good solid anchor text in either side, so:
var match = /data-translate='([^']+)'/.exec(str);
var substr = match && match[1];
Live Example:
var str = "data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'>Avatar data";
var match = /data-translate='([^']+)'/.exec(str);
var substr = match && match[1];
document.body.innerHTML =
"<pre>Got: [" + substr + "]</pre>";
But again, as I said in a comment, using a simple regular expression to extract information from HTML is usually doomed to fail. For instance, you probably don't want to match this:
<p>The string is data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'</p>
...and yet, a simple regex solution will do exactly that. To properly handle HTML, you must use a proper HTML parser.
You can also try this one:
/\'([^\']+)\'/gm

how to replace all occurrence of string between two symbols?

I'm working with RegEx on Javascript and here is where I stuck.
I have a simple string like
<html><body><span style=3D"font-family:Verdana; color:#000; font-size:10pt;=
"><div><font face=3D"verdana, geneva" size=3D"2">http://72.55.146.142:8880/=
order003.png.zip,120</body></html>
all i need to do is write javascript which can replace all strings in with "<" and ">" symbol.
I wrote something like this -
var strReplaceAll = Body;
var intIndexOfMatch = strReplaceAll.indexOf( "<" );
while (intIndexOfMatch != -1){
strReplaceAll = strReplaceAll.replace(/<.*>/,'')
intIndexOfMatch = strReplaceAll.indexOf( "<" );
}
but the problem is if body contains -
test<abc>test2<adg>
it will give me -
test
only or if body contains like -
<html>test<abc>test2<adg>
it will give me nothing please let me know how i can get-
testtest2
as a final output.
Try this regex instead:
<[^>]+>
DEMO:
http://regex101.com/r/kI5cJ7/2
DISCUSSION
Put the html code in a string and apply to this string the regex.
var htmlCode = ...;
htmlCode = htmlCode.replace(/<[^>]+>/g, '');
The original regex take too much characters (* is a greedy operator).
Check this page about Repetition with Star and Plus, especially the part on "Watch Out for The Greediness!".
Most people new to regular expressions will attempt to use <.+>. They will be surprised when they test it on a string like This is a <EM>first</EM> test. You might expect the regex to match <EM> and when continuing after that match, </EM>.
But it does not. The regex will match <EM>first</EM>. Obviously not what we wanted.
/(<.*?>)/
Just use this. Replace all the occurrences with "".
See demo.

jQuery / Javascript replace multiple occurences not working

I'm trying to replace multiple occurrences of a string and nothing seems to be working for me. In my browser or even when testing online. Where am I going wrong?
str = '[{name}] is happy today as data-name="[{name}]" won the match today. [{name}] made 100 runs.';
str = str.replace('/[{name}]/gi','John');
console.log(str);
http://jsfiddle.net/SXTd4/
I got that example from here, and that too wont work.
You must not quote regexes, the correct notation would be:
str = str.replace(/\[{name}\]/gi,'John');
Also, you have to escape the [], because otherwise the content inside is treated as character class.
Updating your fiddle accordingly makes it work.
There are two ways declaring regexes:
// literal notation - the preferred option
var re = /regex here/;
// via constructor
var re = new Regexp('regex here');
You should not put your regex in quotes and you need to escape []
Simply use
str = str.replace(/\[{name}\]/gi,'John');
DEMO
While there are plenty of regex answers here is another way:
str = str.split('[{name}]').join('John');
The characters [ ] { } should be escaped in your regular expression.

Remove all occurrences of text within string

Say I had a string in JavaScript that looked like this:
var str = "Item%5B9%5D.Something%5B0%5D.Prop1=1&Item%5B9%5D.Something%5B0%5D.Prop2=False&Item%5B9%5D.Something%5B0%5D.Prop3=10%2F04%2F2013+00%3A00%3A00&Item%5B9%5D.Something%5B1%5D.Prop1=2&Item%5B9%5D.Something%5B1%5D.Prop2=False&Item%5B9%5D.Something%5B1%5D.Prop3=10%2F04%2F2013+00%3A00%3A00&Item%5B9%5D.Something%5B2%5D.Prop1=3&Item%5B9%5D.Something%5B2%5D.Prop2=False&Item%5B9%5D.Something%5B2%5D.Prop3=29%2F04%2F2013+00%3A00%3A00&Item%5B9%5D.Something%5B3%5D.Prop1=4&Item%5B9%5D.Something%5B3%5D.Prop2=False&Item%5B9%5D.Something%5B3%5D.Prop3=29%2F04%2F2013+00%3A00%3A00"
and wanted it to look like this:
var str = "Something%5B0%5D.Prop1=1&Something%5B0%5D.Prop2=False&Something%5B0%5D.Prop3=10%2F04%2F2013+00%3A00%3A00&Something%5B1%5D.Prop1=2&Something%5B1%5D.Prop2=False&Something%5B1%5D.Prop3=10%2F04%2F2013+00%3A00%3A00&Something%5B2%5D.Prop1=3&Something%5B2%5D.Prop2=False&Something%5B2%5D.Prop3=29%2F04%2F2013+00%3A00%3A00&Something%5B3%5D.Prop1=4&Something%5B3%5D.Prop2=False&Something%5B3%5D.Prop3=29%2F04%2F2013+00%3A00%3A00"
i.e. remove all of the Item%5BX%5D. parts
How would I go about doing this? I thought of using something like:
str = str.substring(str.indexOf('Something'), str.length);
but obviously that only removes the first occurrence.
Also the number in-between the %5B and %5D could be anything, not necessarily 9.
This seems like something that should be simple but for some reason I'm stumped. I found a few similarish things on SO but nothing that handled all the above criteria.
You could use a regular expression :
str = str.replace(/Item[^.]+\./g, '');
or if you want something more precise because you'd want to keep Item%6B3%4D :
str = str.replace(/Item%5B.%5D\./g, '');
str = str.replace('Item%5B9%5D', '');
EDIT: Missed the part where 9 in the string could be any number. You can use:
str = str.replace(/Item%5B\d%5D\./g, '');
Avoid using a regular expression where complex "needle" escaping is required:
var str = "something complex full of http://, 'quotes' and more keep1 something complex full of http://, 'quotes' and more keep2 something complex full of http://, 'quotes' and more keep3"
var needle = "something complex full of http://, 'quotes' and more";
while( str.indexOf(needle) != '-1')
str = str.replace(needle,"");
document.write(str);
Outputs:
keep1 keep2 keep3
Here you go:
str = str.replace(/Item%5B\d%5D\./g,'');
Live Demo
Try using regular expressions:
str = str.replace(/Item%5B[^.]*%5D./g, '');
This assumes that you can have anything of any length between %5B and %5D.
JSFiddle
Using split() & join() method
var str = "Item%5B9%5D.Something%5B0%5D.Prop1=1&Item%5B9%5D.Something%5B0%5D.Prop2=False&Item%5B9%5D.Something%5B0%5D.Prop3=10%2F04%2F2013+00%3A00%3A00&Item%5B9%5D.Something%5B1%5D.Prop1=2&Item%5B9%5D.Something%5B1%5D.Prop2=False&Item%5B9%5D.Something%5B1%5D.Prop3=10%2F04%2F2013+00%3A00%3A00&Item%5B9%5D.Something%5B2%5D.Prop1=3&Item%5B9%5D.Something%5B2%5D.Prop2=False&Item%5B9%5D.Something%5B2%5D.Prop3=29%2F04%2F2013+00%3A00%3A00&Item%5B9%5D.Something%5B3%5D.Prop1=4&Item%5B9%5D.Something%5B3%5D.Prop2=False&Item%5B9%5D.Something%5B3%5D.Prop3=29%2F04%2F2013+00%3A00%3A00";
console.log(str.split(/Item%5B\d%5D\./g).join(''));

Categories