javascript - replace dash (hyphen) with a space - javascript

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

Related

add an element "/" in particular position in string with Javascript

I want to add an element "/" within a string, but only a specific position of it, e.g. from string "20180101" to expect result like "2018/01/01".is anyone know what syntax or how to make it happen.I'm still beginner in javascript
any help would be really appreciate.
Here is one option using replace with a regex pattern:
var input = "20180419";
console.log(input.replace( new RegExp("^(\\d{4})(\\d{2})(\\d{2})", "gm"),"$1/$2/$3"));
Use substr approach to get the result:
var str = "20180101";
str = str.substr(0, str.length-4) + '/' + str.substr(4, str.length);
str = str.substr(0, str.length-2) + '/' + str.substr(7, str.length);;
console.log(str);
Another option creating an array of sub-strings with slice (note that this would work the same way with substring here), and then joining each part with a /:
let s = "20180101"
let result = [s.substring(0,4), s.substring(4,6), s.substring(6,8)].join('/')
In such cases, you may find useful to treat your string as an array of digits.
Get an array of digits from your string:
let myString = '20180101';
let myArray = myString.split('') //the '' splitter means it will just split anything
Then, add into your array of digits, the desired '/' digit in the desired positions. Refer to the splice method for more information.
myArray.splice(4,0,'/');
myArray.splice(7,0,'/');
Then, build your string:
myString = myArray.join(''); //the opposite of splitting
console.log(myString) // outputs '2018/01/01'

Extract Twitter handlers from string using regex in JavaScript

I Would like to extract the Twitter handler names from a text string, using a regex. I believe I am almost there, except for the ">" that I am including in my output. How can I change my regex to be better, and drop the ">" from my output?
Here is an example of a text string value:
"PlaymakersZA, Absa, DiepslootMTB"
The desired output would be an array consisting of the following:
PlaymakersZA, Absa, DiepslootMTB
Here is an example of my regex:
var array = str.match(/>[a-z-_]+/ig)
Thank you!
You can use match groups in your regex to indicate the part you wish to extract.
I set up this JSFiddle to demonstrate.
Basically, you surround the part of the regex that you want to extract in parenthesis: />([a-z-_]+)/ig, save it as an object, and execute .exec() as long as there are still values. Using index 1 from the resulting array, you can find the first match group's result. Index 0 is the whole regex, and next indices would be subsequent match groups, if available.
var str = "PlaymakersZA, Absa, DiepslootMTB";
var regex = />([a-z-_]+)/ig
var array = regex.exec(str);
while (array != null) {
alert(array[1]);
array = regex.exec(str);
}
You could just strip all the HTML
var str = "PlaymakersZA, Absa, DiepslootMTB";
$handlers = str.replace(/<[^>]*>|\s/g,'').split(",");

Javascript (Regex): How do i replace (Backslash + Double Quote) pairs?

In Javascript, i want the below original string:
I want to replace \"this\" and \"that\" words, but NOT the one "here"
.. to become like:
I want to replace ^this^ and ^that^ words, but NOT the one "here"
I tried something like:
var str = 'I want to replace \"this\" and \"that\" words, but NOT the one "here"';
str = str.replace(/\"/g,"^");
console.log( str );
Demo: JSFiddle here.
But still .. the output is:
I want to replace ^this^ and ^that^ words, but NOT the one ^here^
Which means i wanted to replace only the \" occurrences but NOT the " alone. But i cannot.
Please help.
As #adeneo's comment, your string was created wrong and not exactly like your expectation. Please try this:
var str = 'I want to replace \\"this\\" and \\"that\\" words, but not the one "here"';
str = str.replace(/\\\"/g,"^");
console.log(str);
You can use RegExp /(")/, String.prototype.lastIndexOf(), String.prototype.slice() to check if matched character is last or second to last match in input string. If true, return original match, else replace match with "^" character.
var str = `I want to replace \"this\" and \"that\" words, but NOT the one "here"`;
var res = str.replace(/(")/g, function(match, _, index) {
return index === str.lastIndexOf(match)
|| index === str.slice(0, str.lastIndexOf(match) -1)
.lastIndexOf(match)
? match
: "^"
});
console.log(res);
The problem with String.prototype.replace is that it only replaces the first occurrence without Regular Expression. To fix this, you need to add a g and the end of the RegEx, like so:
var mod = str => str.replace(/\\\"/g,'^');
mod('I want to replace \\"this\\" and \\"that\\" words, but NOT the one "here"');
A less effective but easier to understand to do what you wanted is to split the string with the delimiter and then join it with the replacement, like so:
var mod = str => str.split('\\"').join('^');
mod('I want to replace \\"this\\" and \\"that\\" words, but NOT the one "here"');
Note: You can wrap a string with either ' or ". Suppose your string contains ", i.e. a"a, you will need to put an \ in front of the " as "a"a" causes syntax error. 'a"a' won't cause syntax error as the parser knows the " is part of the string, but when you put a \ in front of " or any other special characters, it means the following character is a special character. So 'a\"a' === 'a"a' === "a\"a". If you want to store \, you will need to use \ regardless of the type of quote you use, so to store \", you will need to use '\\"', '\\\"' or "\\\"".

Get last occurrence using RegEx

I have a huge string with this inside:
linha[0] = '12/2010 281R$ 272.139,05 ';
linha[0] = '13SL 1R$ 226.185,81 ';
Both lines are separate, and I need get the last occurrence from both. I'm using the following regex to match the first one:
/linha\[0]\s=\s'(.*)';/
I would like to get the second "linha..." too, but I don't know exactly how.
That's how i'm using this regex to get the first "linha...":
string.match(/linha\[0]\s=\s'(.*)';/);
output:
linha[0] = '12/2010 281R$ 272.139,05 ';
Also, i can't do extra work, i need get the second occurrence using only regex.
If you want to get the last occurrence of your regex in a string (and assuming it exists), you can do
var str = hugeString.match(/linha\[0]\s=\s'([^']*)';/g).pop();
(yes, I changed .* to [^']* for a better efficiency, ignore that if you have quotes in your inner string)
Now, if you want to extract just the submatch, you can do
var regex = /linha\[0]\s=\s'([^']*)';/g,
arr,
str;
while (arr = regex.exec(hugeString)) str = arr[1];

RegExp match a single quoted text without quotes - JavaScript

I'm sorry if it is a confusing question. I was trying to find a way to do this but couldn't find it so, if it is a repeated question, my apologies!
I have a text something like this: something:"askjnqwe234"
I want to be able to get askjnqwe234 using a RegExp. You can notice I want to omit the quotes. I was trying this using /[^"]+(?=(" ")|"$)/g but it returns an array. I want a RegExt to return a single string, not an array.
I don't know if it's possible but I do not want to specify the position of the array; something like this:
var x = string.match(/[^"]+(?=(" ")|"$)/g)[0];
Thanks!
Try:
/"([^"]*)"/g
in English: look for " the match and record anything that isn't " till you see another "".
match and exec always return an array or null, so, assuming you have a single double-quoted value and no newlines in the string, you could use
var x;
var str = 'something:"askjnqwe234"';
x = str.replace( /^[^"]*"|".*/g, '' );
// "askjnqwe234"
Or, if you may have other quoted values in the string
x = str.replace( /.*?something:"([^"]*)".*/, '$1' );
where $1 refers to the substring captured by the sub-pattern [^"]* between the ().
Further explanation on request.
Notwithstanding the above, I recommend that you tolerate the array indexing and just use match.
You can capture the information inside quotes like this, assuming it matches:
var x = string.match(/something:"([^"]*)"/)[1];
The memory capture at index 1 is the part inside the double quotes.
If you're not sure it will match:
var match = string.match(/something:"([^"]*)"/);
if (match) {
// use match[1] here
}

Categories

Resources