Replace function only works once (javascript) - javascript

I need to replace a string (str1) with another string (str2) every time str1 shows in a specific div.
This is what I got so far
<script type="text/javascript">
$(window).load(function(){
var str=document.getElementById("foo").innerHTML;
var n=str.replace("Google","Yahoo");
document.getElementById("foo").innerHTML=n;
});
</script>
and the html
<div id="foo">
Google is the best website ever <br />
Google is not the best website ever</div>
Unfortunately, when I run it, it only replaces the first instance of the word Google.
What am I doing wrong? What do I need to add to make it replace ALL the instances of the word?

Use regex /string/g to replace all occurrences, you are using substring which will replace only first occurances as per documentation of replace() function.
Live Demo
var n=str.replace(/Google/g,"Yahoo");
String.prototype.replace()
The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.
str.replace(regexp|substr, newSubStr|function)
You are using substr pattern which will replace first occurance only.
substr (pattern)
A String that is to be replaced by newSubStr. It is treated as a
verbatim string and is not interpreted as a regular expression. Only
the first occurrence will be replaced.
Use this regexp patter to replace all occurances.
regexp (pattern)
A RegExp object or literal. The match is replaced by
the return value of parameter #2.

Related

reactStringReplace() inconsistent regex match

I'm trying to use react-string-replace to match all $Symbols within a string of text.
Here are a few example values we'd like to be matched (stock / crypto / forex pairs): $GPRO, $AMBA, $BTC/USD, $LTC/ETH
Here is our attempted regex
/\$\S+[^\s]*/g
when passing the string
$this works great $this/works great too.
through .match() - the proper symbols are returned in an array.
0: "$this"
1: "$this/works"
When using
reactStringReplace() - each match is returning
works great
Any ideas why
reactStringReplace()
seems to be handling this regex incorrectly?
Thanks ya'll!
Check the React String Replace documentation, it is written there:
reactStringReplace(string, match, func)
...
match
Type: regexp|string
The string or RegExp you would like to replace within string. Note that when using a RegExp you MUST include a matching group.
Why should you add a capturing group? See the replaceString function. There is var result = str.split(re); line that uses the pattern to actually split the contents you pass to the regex with your pattern thus tokenizing the whole input into parts that match and those that do not match your regex.
If you do not add a group to the regex passed as a String, the capturing parentheses will be added automatically around the whole pattern:
if (!isRegExp(re)) {
re = new RegExp('(' + escapeRegExp(re) + ')', 'gi');
}
If you pass your regex as a RegExp without capturing parentheses, the matches will be missing from the resulting array, hence, they will disappear.
So, use
/(\$\S+)/g
If you want to keep the $ chars in the output, or
/\$(\S+)/g
if you want to omit the dollars.

how to remove just one character in a string of javascript

#a:{width:100px;height:100px;background-color:black;}#b:{width:100px;}
i have the above string
i want that the character: only after css selector like #a and #b get removed from this string
i thought that i must use regular expressions so i wrote one:
/[#\.A-Za-z0-9]+([:])[{]/g
see this regular expression working on regex101
but you know it matches : but when i try to remove this using replace method then whole #a:{ and #b:{ get removed
any help would be great!
The regex is almost correct. What you need to do is to repalce the with $1$2 instead of null string
Also make a small change to the regex as
/([#.A-Za-z0-9]+):({)/g
Regex Example
Changes made
([#.A-Za-z0-9]+) enclosed in brackets. The matched string is captured in $1 hence for the frist match $1 will contain #a
Within a character class its not required to escape the . as it looses it meaning in the class.
[{] to ({) The [] surrounding does not make any difference, hence drop it. Enclosed in (), hence captured in $2, for example in first match the $2 will contian {
Replace string $1$2
will give output as
#a{width:100px;height:100px;background-color:black;} #b{width:100px;}
Javascript
var value = "#a:{width:100px;height:100px;background-color:black;}#b:{width:100px;}";
alert(value.replace(/(#.):/g, "$1"));
Example: http://jsfiddle.net/7hs0jgd2/

JavaScript regexp not matching

I am having a difficult time getting a seemingly simple Regexp. I am trying to grab the last occurrences of word characters between square brackets in a string. My code:
pattern = /\[(\w+)\]/g;
var text = "item[gemstones_attributes][0][shape]";
if (pattern.test(text)) {
alert(RegExp.lastMatch);
}
The above code is outputting "gemstones_attributes", when I want it to output "shape". Why is this regexp not working, or is there something wrong with my approach to getting the last match? I'm sure that I am making an obvious mistake - regular expressions have never been my string suit.
Edit:
There are cases in which the string will not terminate with a right-bracket.
You can greedily match as much as possible before your pattern which will result in your group matching only the last match:
pattern = /.*\[(\w+)\]/g;
var text = "item[gemstones_attributes][0][shape]";
var match = pattern.exec(text);
if (match != null) alert(match[1]);
RegExp.lastMatch gives the match of the last regular expression. It isn't the last match in the text.
Regular expressions parse left to right and are greedy. So your regexp matches the first '[' it sees and grabs the words between it. When you call lastMatch it gives you the last pattern matched. What you need is to match everything you can first .* and then your pattern.
i think your problem is in your regex not in your src line .lastMatch.
Your regex returns just the first match of your square brackets and not all matches. You can try to add some groups to your regular expression - and normally you should get all matches.
krikit
Use match() instead of test()
if (text.match(pattern))
test() checks for a match inside a string. This is successfull after the first occurence, so there is no need for further parsing.

How do I ignore $1 replace backreferencing in javascript

I have a string that a user can edit at any time, and a regex that is being conducted on the string, to add it to an xml and then save it but they can add '$1' to the string. I just want the text '$1' to be saved but I have to perform a regular expression on the same string that $1 is in. It replaces the $1 with a character from the regex every time.
How do I find, and replace, the $1 in this string?
Example of what is happening:
string1 = '<item id="1">i have $100</item>'
regexp = new RegExp('<item id="1"([^<]|<[^\/]|<\/[^i]|<\/i[^t]|<\/it[^e]|<\/ite[^m]|<\/item[^>])*<\/item>');
data = '<data><item id="1">i have no money</item><item id="2">i have no money</item></data>'
data = data.replace(regexp, string1);
Results
<data><item id="1">i have >00</item><item id="2">i have no money</item></data>
If you have a variable string that you want to put in your replace() call which might possibly have $N's in it, you can prevent the $N from being treated as a backreference by replacing $ with $$. Apparently, unlike other special characters in JS regex, the $ character cannot be escaped with a \ - it must be escaped with a preceding $ (go figure).
In your example, you could do the following to fix the issue:
data = data.replace(regexp, string1.replace('$', '$$$'));
This should turn any $'s into $$ in string1, preventing them from being treated as backreferences.
(Note: I found this little nugget here)
This should only happen if you have a capturing group in the regex.
If you don't want your groups to capture, then place ?: inside the start of the group.
/foo(?:bar)/
You can escape the $. Eg:
var replacement = '<item id="1">i have \\$100</item>';
Useful when you have capturing groups and need to write a $.

How to remove periods in a string using jQuery

I have the string R.E.M. and I need to make it REM
So far, I have:
$('#request_artist').val().replace(".", "");
...but I get RE.M.
Any ideas?
The first argument to replace() is usually a regular expression.
Use the global modifier:
$('#request_artist').val().replace(/\./g, "");
replace() at MDC
You could pass a regular expression to the replace method and indicate that it should replace all occurrences like this: $('#request_artist').val().replace(/\./g, '');
The method used to replace the string is not recursive, meaning once it found a matching char or string, it stop looking. U should use a regular expression replace. $("#request_artist").val().replace(/\./g, ''); Check out Javascript replace tutorial for more info.

Categories