The question is, that if i have a string, i.e:
"--Julius.",
and I want replace "-" and ".". How i can get it?
Finally, I get:
"Julius"
This question have an easy solution. You only do the next:
word="--Julius."
word.replace("--", "")
word.replace(".", "")
print(word)
Output:
"Julius"
This is specific for the JavaScript.:
var str ='--Julius.';
str = str.replace(/[-.]/g, function(m) { return {'-':'','.':''}[m]; });
console.log(s);
We can use the .replace(oldvalue, newvalue) function and replace multiple characters in a string in the similar manner:
var str ='--Julius.';
str = str.replace(/[-.]/g, '');
console.log(str);
We could use this instead to replace all the character with the same character.
Related
My question is how can I replace the character from a given string?
If someone says something in the chat, and that word is a bad word then replace it with "****".
I don't know how to approach the print section.. Because I've got the index of the badword but I don't know how to replace it from the original message.
local badwords = {
"badword",
"badword2",
}
function(msg)
local message = msg;
local lowered_msg = message:lower();
for index, val in pairs(badwords) do
if lowered_msg:match(val) then
local indexStart, indexEnd = string.find(lowered_msg, val)
print(message:gsub(indexStart, "*****", indexEnd))
end
end
end
The gsub function takes three arguments:
the string to be modified,
the pattern to be replaced,
and the replacement string,
so you need to do something like this:
message = string.gsub(message, message:sub(indexStart, indexEnd), "*****")
print(message)
This Way use a table with badwords and replacements for gsub.
local badwords = {fair='f**r', foul='f**l'}
print(('fair is foul and foul is fair'):gsub('%w+', badwords))
...if the pattern matches words.
gsub() loops over the whole string except the 4th argument is used
I wanted to split a string using regex expression.
The string is:
var str = 'i want #masala tea#'
I want this string to be splitted into the array ['i want','masala tea']
What I have tried so far was:
var arr = str.split(/^#.*#$/);
but this did not work.
Don't use spilt function for this case. use replace funtion like this:
var str='i want #masala tea#';
console.log(str.replace(/#/gi, "")); //i want masala tea.
Thanks.
You can split your message on each '#' and then filter empty items. If you need to remove whitespace characters from each string use .map(...) function.
'i want #masala tea#'.split('#').filter(e => e != "");
//["i want ", "masala tea"]
'i want #masala tea#'.split('#').map(e => e.trim()).filter(e => e != "");
//["i want", "masala tea"]
Yes, you can split string using regex expression.
Try this. i thing it will solve your problem.
let yourString = 'i want #masala tea#'; // your string
// function that return exactly what you want
let outputArr = (string) => {
return string.trim().match(/[^#]+/g).map(item => item.trim());
}
console.log(outputArr(yourString));
//(2) ["i want", "masala tea"]
So I am learning Kotlin now, and I was trying to do a calculator where if we can give expression like 4+3 or 3*5 and we will get the answer so I was trying to split that input string and then find what operator is used and what are the operands.
var list = str.split("+","-","*","/" )
so how can i get the delimiter that is used to split that string too.
I'm afraid that split method doesn't have this feature. You would have to split the the string via separate split calls. And compare the outcome with original string. If the string wasn't split by given delimiter that outcome should be the same.
Eg. like this:
var str = "5+1"
var delimiters = arrayOf("+","-","*","/")
var found = "Not found"
for (delimiter in delimiters) {
var splited = str.split(delimiter)
if(splited[0] != str) {
found = delimiter
break
}
}
println(found)
I have this string:
Some text: $ 12.3 9
I want to get as a result:
12.39
I have found examples on how to keep only numbers, but here I am wanting to keep the decimal point "."
What's a good way to do this in Swift?
This should work (it's a general approach to filtering on a set of characters) :
[EDIT] simplified and adjusted to Swift3
[EDIT] adjusted to Swift4
let text = "$ 123 . 34 .876"
let decimals = Set("0123456789.")
var filtered = String( text.filter{decimals.contains($0)} )
If you need to ignore anything past the second decimal point add this :
filtered = filtered.components(separatedBy:".") // separate on decimal point
.prefix(2) // only keep first two parts
.joined(separator:".") // put parts back together
Easiest and simplest reusable way: you can use this regex replacement option. This replaces all characters except 0 to 9 and dot (.) .
let yourString = "$123. 34"
//pattern says except digits and dot.
let pattern = "[^0-9.]"
do {
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive)
//replace all not required characters with empty string ""
let string_With_Just_Numbers_You_Need = regex.stringByReplacingMatchesInString(yourString, options: NSMatchingOptions.WithTransparentBounds, range: NSMakeRange(0, yourString.characters.count), withTemplate: "")
//your number converted to Double
let convertedToDouble = Double(string_With_Just_Numbers_You_Need)
} catch {
print("Cant convert")
}
One possible solution to the question follows below. If you're working with text fields and currency, however, I suggest you take a look at the thread Leo Dabus linked to.
extension String {
func filterByString(myFilter: String) -> String {
return String(self.characters.filter {
myFilter.containsString(String($0))
})
}
}
var a = "$ 12.3 9"
let myFilter = "0123456789.$"
print(a.filterByString(myFilter)) // $12.39
Dart provide us a new way to concate strings without the + operator.
Old way would be:
String foo = "foo";
String newString = "Hello" + " foo " + "bar";
The dart way would be:
String foo = "foo";
String newString = "Hello $foo bar";
Both would result in:
Hello foo bar
But, what if I want to concatenate without spaces?
Old way would be:
String foo = "foo";
String newString = "Hello" + "foo" + "bar";
Result would be:
Hellofoobar
But when I try this at Dart, it gives me an obviously syntax error:
String foo = "foo";
String newString = "Hello $myString bar";
What is the solution to this? Should I use the String.concat? A string buffer? I really liked this new way to concatenate Strings, but I don't think I could use to this kind of situation.
Thanks in advance.
Multiple options exist.
First instead of using the + you can just have multiple string literals:
String str = 'foo' ' bar ' 'zap'; // any whitespace between literals
Secondly if you want to use string interpolation, you can just as the parens to help with scope:
String foo = 'foo';
String str = 'Hello${foo}bar';