Split a string using regex expression in node js - node.js

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"]

Related

How to replace string in lua?

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

How to replace a character in a string?

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.

how to separate a string char by char and add a symbol after in c#

Any idea how i can separate a string with character and numbers, for example
12345ABC678 to make it look like this
1|2|3|4|5|A|B|C|6|7|8??
Or if this is not possile, how can i take this string a put every character or nr of it in a different textBox like this?
You can use String.Join and String.ToCharArray:
string input = "12345ABC678";
string result = String.Join("|", input.ToCharArray());
Instead of ToCharArray(creates a new array) you could also cast the string to IEnumerable<char> to force it to use the right overload of String.Join:
string result = String.Join("|", (IEnumerable<char>)input);
use
String aString = "AaBbCcDd";
var chars = aString.ToCharArray();
Then you can loop over the array (chars)

How to Split a string with a set of delimiters and find what delimiter it was? Kotlin

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)

Swift string strip all characters but numbers and decimal point?

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

Resources