Replace all spaces in a string with '+'
Here's an alternative that doesn't require regex:
var str = 'a b c';
var replaced = str.split(' ').join('+');
How to replace all spaces in a string
var result = replaceSpace.replace(/ /g, ";");
Here, / /g
is a regex (regular expression). The flag g
means global. It causes all matches to be replaced.
Replace all spaces in a string with +
Use strings.ReplaceAll
tw.Text = strings.ReplaceAll(tw.Text, " ", "+")
If you're using an older version of go (< 1.12), use strings.Replace
with -1
as limit (infinite)
tw.Text = strings.Replace(tw.Text, " ", "+", -1)
Replace all plus signs (+) with space in a string
The +
character has special significance in regular expressions. It's a quantifier meaning one or more of the previous character, character class, or group.
You need to escape the +
, like this:
i.replace(new RegExp("\\+","g"),' ')...
Or more simply, by using a precompiled expression:
i.replace(/\+/g,' ')...
Write a method to replace all spaces in a string with '%20'
You are passing the length as 6, which is causing this. Pass length as 7 including space.
Other wise
for(i = length - 1; i >= 0; i--) {
will not consider last char.
How to replace spaces middle of string in Dart?
Using RegExp like
String result = _myText.replaceAll(RegExp(' +'), ' ');
Write a method to replace all spaces in a string with '%20'?
In this loop, the program adds %20
before each word:
for(String w: words){
sentence.append("%20");
sentence.append(w);
}
That will produce incorrect results, for example for a b
it will give %20a%20b
.
There's a much simpler solution:
public String replace(String str) {
return str.replaceAll(" ", "%20");
}
Or, if you really don't want to use .replaceAll
, then write like this:
public String replace(String str) {
String[] words = str.split(" ");
StringBuilder sentence = new StringBuilder(words[0]);
for (int i = 1; i < words.length; ++i) {
sentence.append("%20");
sentence.append(words[i]);
}
return sentence.toString();
}
Related Topics
Jquery Get Values of Checked Checkboxes into Array
Jquery Drop Down Menu Closing by Clicking Outside
Random Number Generator Without Dupes in JavaScript
Assign Variable in If Condition Statement, Good Practice or Not
What Is Property in Hasownproperty in JavaScript
Angularjs $Resource Restful Example
What's Pros and Cons: Putting JavaScript in Head and Putting Just Before the Body Close
How to Open a Popup with JavaScript and Then Detect When the User Closes It
How to JSON Stringify a JavaScript Date and Preserve Timezone
How to Access Object Property with Invalid Characters
$.Each() VS For() Loop - and Performance
Regex Pattern to Match the End of a String
How to Detect Timeout on an Ajax (Xmlhttprequest) Call in the Browser
Google Bar Chart Cannot Change Individual Bar Color
How to Disable Right-Click Context-Menu in JavaScript