Replace the last symbols of string [duplicate] - javascript

I'm having a problem finding out how to replace the last ', ' in a string with ' and ':
Having this string:
test1, test2, test3
and I want to end out with:
test1, test2 and test3
I'm trying something like this:
var dialog = 'test1, test2, test3';
dialog = dialog.replace(new RegExp(', /g').lastIndex, ' and ');
but it's not working

foo.replace(/,([^,]*)$/, ' and $1')
use the $ (end of line) anchor to give you your position, and look for a pattern to the right of the comma index which does not include any further commas.
Edit:
The above works exactly for the requirements defined (though the replacement string is arbitrarily loose) but based on criticism from comments the below better reflects the spirit of the original requirement.
console.log(
'test1, test2, test3'.replace(/,\s([^,]+)$/, ' and $1')
)

result = dialog.replace(/,\s(\w+)$/, " and $1");
$1 is referring to the first capturing group (\w+) of the match.

regex search pattern \s([^,]+)$
Line1: If not, sdsdsdsdsa sas ., sad, whaterver4
Line2: If not, fs sadXD sad , ,sadXYZ!X
Line3: If not d,,sds,, sasa sd a, sds, 23233
Search with patterns finds
Line1: whaterver4
Line3: 23233
Yet doesnt find Line2: sadXYZ!X
Which is only missing a whitespace

Related

RegEx Split String and Leave Delimiter

I am trying to split a string and leave the delimiter intact. I am getting pretty close but I can't figure it out fully. I have found a lot of examples on Stack Overflow but I am still running in to an issue that I can't figure out. Here is the code:
"This is a string with ${G:VarSome:G} text".split(/\$\{(.+?(}\(.+?\)|}))/g)
The above code yields:
['This is a string with ', 'G:VarSome:G}', '}', ' text']
The result I am looking for is:
['This is a string with ', '${G:VarSome:G}', ' text']
The ${G:SomeVar:G} pattern is a templating system where variables will be injected. There are other formats of variables too for example ${G:AnotherVar:1}, ${G:DifferentVar:5} etc. After I get the split string, I will do a variable lookup in the system to inject the corresponding variable.
You are having an extra capture group inside the regex, this will give you a single group.
const result = "This is a string with ${G:VarSome:G} text".split(/(\${.+?})/g);
console.log(result);
The regex that graps a single capture group looks like this. it returns all the captured inside ()
/(\${.+?})/g
This should capture the examples provided. regex101
It's build with first getting
${ and then getting one or more characters lazily (.+?) until it encounters a }.
You can use this regex for splitting:
/(\${[^}]*})/
Code:
var s = 'This is a string with ${G:VarSome:G} text';
var arr = s.split(/(\${[^}]*})/);
console.log(arr);
Here:
\${[^}]*}: Will match ${ followed by 0 or more non-} characters followed by }

Chain replace for the same character appearing multiple times

Let's say I have a string like so
Danny is ? James is ? Allen is ?
And I want to replace it to
Danny is great James is wonderful Allen is magnificent
How can I use replace to do it?
I'm attempting to do something like
string.replace(/\?/g, 'great ').replace(/\?/g, 'wonderful ').replace(/\?/g, 'magnificent');
but I just get:
Danny is great James is great Allen is great
If the case was something like:
Danny is ? James is # Allen is $
string.replace(/\?/g, 'great ').replace(/\#/g, 'wonderful ').replace(/\$/g, 'magnificent');
It would work as expected, but since it's the same character it's not working.
Is there a neater way to achieve this than doing something like below?
string = string.replace(/\?/g, 'great ')
string = string.replace(/\?/g, 'wonderful ')
string = string.replace(/\?/g, 'magnificent');
You are using the replace function with a regular expression with the /g (meaning: "global") option, which means it will replace the '?' everywhere in the string.
To replace only one occurence of '?' at a time, just use a normal string to find, eg: string.replace('?', 'great')
So, your full example would be:
string = string.replace('?', 'great ')
string = string.replace('?', 'wonderful ')
string = string.replace('?', 'magnificent');

Split string into array but still keep it's comma when applying join. - Javascript

I'm having a hard time remembering how to split a string while still keeping the comma in the string and splitting special cases as well.
Example of what I'm trying to do is this:
> Input: "Welcome, <p>how<b>are you</p>do-ing</b>?"
> Output: ["Welcome,", " ", "<p>", "how", "<b>", "are you", "</b>", "</p>", "do-ing", "</b>", "?"]
What I have tried:
var str = "Welcome, <p>how<b>are you</p>doing</b>?",
arr = str.split(/([,\s])/);
Unfortunately the only way I can think about splitting the special cases is replace them with comma's before and after them, but all this does is cause problems trying to keep the original comma. I've been scratching my head at this and I know it's right in front of me. I have tried looking all over for examples or answers and I'm drawing a blank in what I'm trying to look for.
Use .match instead of .split:
var str = "Welcome, <p>how<b>are you</p>doing</b>?",
arr = str.match(/<[^>]+>|[^,<]+,?/g);
console.log(arr);
The pattern <[^>]+>|[^,<]+,? means:
Alternate between
<[^>]+> - Match < followed eventually by a >, or
[^,<]+,? - Match characters other than , and <, optionally followed by a ,

How to create whitespace inside a JSON

I want to put a line of space or blanks between the values. Because they're all leaving together right now.
My example:
data: JSON.stringify({
"sessionID":xxxxx,
"synchronize":false,
"sourceRequest":{
"numberOrigin":xxxxxx,
"type":"x",
"description":test + "\\n" + test2 "\\n" + test3 "\\n" + test4,
"userID":xxxxxxxx,
"contact":{
"name":"xxxxxxxxxxxxxxxxx",
"phoneNumber":"xxxxxxxxxx",
"email":xxxx,
"department":"xxxxx"
},
The "\\n" says to put a literal \n in the string - 2 chars. You should just use "\n" to say that its a new line - 1 char.
Note if viewing in Windows Notepad, \n is not enough for a new line.
A simple ' ' (space character) is enough to do what is needed, the json key does hold a string after all, if you need something more prominent you can use '\t', refer here for more.

javascript - replace dash (hyphen) with a space

I have been looking for this for a while, and while I have found many responses for changing a space into a dash (hyphen), I haven't found any that go the other direction.
Initially I have:
var str = "This-is-a-news-item-";
I try to replace it with:
str.replace("-", ' ');
And simply display the result:
alert(str);
Right now, it doesn't do anything, so I'm not sure where to turn. I tried reversing some of the existing ones that replace the space with the dash, and that doesn't work either.
Thanks for the help.
This fixes it:
let str = "This-is-a-news-item-";
str = str.replace(/-/g, ' ');
alert(str);
There were two problems with your code:
First, String.replace() doesn’t change the string itself, it returns a changed string.
Second, if you pass a string to the replace function, it will only replace the first instance it encounters. That’s why I passed a regular expression with the g flag, for 'global', so that all instances will be replaced.
replace() returns an new string, and the original string is not modified. You need to do
str = str.replace(/-/g, ' ');
I think the problem you are facing is almost this: -
str = str.replace("-", ' ');
You need to re-assign the result of the replacement to str, to see the reflected change.
From MSDN Javascript reference: -
The result of the replace method is a copy of stringObj after the
specified replacements have been made.
To replace all the -, you would need to use /g modifier with a regex parameter: -
str = str.replace(/-/g, ' ');
var str = "This-is-a-news-item-";
while (str.contains("-")) {
str = str.replace("-", ' ');
}
alert(str);
I found that one use of str.replace() would only replace the first hyphen, so I looped thru while the input string still contained any hyphens, and replaced them all.
http://jsfiddle.net/LGCYF/
In addition to the answers already given you probably want to replace all the occurrences. To do this you will need a regular expression as follows :
str = str.replace(/-/g, ' '); // Replace all '-' with ' '
Use replaceAll() in combo with trim() may meet your needs.
const str = '-This-is-a-news-item-';
console.log(str.replaceAll('-', ' ').trim());
Imagine you end up with double dashes, and want to replace them with a single character and not doubles of the replace character. You can just use array split and array filter and array join.
var str = "This-is---a--news-----item----";
Then to replace all dashes with single spaces, you could do this:
var newStr = str.split('-').filter(function(item) {
item = item ? item.replace(/-/g, ''): item
return item;
}).join(' ');
Now if the string contains double dashes, like '----' then array split will produce an element with 3 dashes in it (because it split on the first dash). So by using this line:
item = item ? item.replace(/-/g, ''): item
The filter method removes those extra dashes so the element will be ignored on the filter iteration. The above line also accounts for if item is already an empty element so it doesn't crash on item.replace.
Then when your string join runs on the filtered elements, you end up with this output:
"This is a news item"
Now if you were using something like knockout.js where you can have computer observables. You could create a computed observable to always calculate "newStr" when "str" changes so you'd always have a version of the string with no dashes even if you change the value of the original input string. Basically they are bound together. I'm sure other JS frameworks can do similar things.
if its array like
arr = ["This-is-one","This-is-two","This-is-three"];
arr.forEach((sing,index) => {
arr[index] = sing.split("-").join(" ")
});
Output will be
['This is one', 'This is two', 'This is three']

Categories

Resources