Javascript - 按空格分割字符串,并按" |"加入两个单词

时间:2018-02-11 10:41:09

标签: javascript extendscript

我认为这很容易,但我无法弄清楚。

$output  .= '<div class="hotel-container">
                                    <div class="row">
                                        <div class="col-md-4">  
                                            <img src="admin/'.$row['main_picture'].'"class="img-responsive hotelpic">
                                        </div>

                                        <div class="col-md-5">
                                            <h5 class="hotelname">'.$row['resort_name'].'</h5>
                                            <h5 class="address"><i class="fa fa-map-marker" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;'.$row['resort_address'].'</h5>
                                        </div>

                                        <div class="col-md-3">
                                            <h5 class="price">&#8369; '.$row['resort_total_cost'].'</h5>
                     /*here's the button*/  <button class="btn btn-warning" id="viewinfo">View more info</button>
                                        </div>
                                    </div>

                                </div>';

结果将是:var str = "How are you doing today?"; var res = str.split(/\s+/g); 。当用户添加字符&#34; |&#34;在这两个词之间

How,are,you,doing,today?

结果应该是:var str = "How are you |doing today?";

3 个答案:

答案 0 :(得分:0)

试试这个:

var source = "How are you |doing today?";
var result = source
  .split(/\s+(?!\|)/g)
  .map(function(segment) {
    return segment.replace(/((\s+)\|)/g, '$2');
  });
  
console.log(result);

首先使用否定先行将字符串split放到管道符(|未跟踪的空格序列上,然后结果数组被映射,例如每个段的空格序列后面跟着一个管道字符,只替换每个匹配组($2)的空白部分($1)。

如果在Extendscript中没有实现Array.map,这是使用常规for循环的另一个示例:

var source = "How are you |doing today?";
var rawArray = source.split(/\s+(?!\|)/g);
var result = [];

for (var i = 0; i < rawArray.length; i++) {
  result[i] = rawArray[i].replace(/((\s+)\|)/g, '$2');
}
  
console.log(result);

答案 1 :(得分:0)

您无法执行 split所描述的内容。你可以使用负前瞻断言(/ (?!\|)/)来接近,但它会在字符串中留下|

var str = "How are you |doing today?";
var arr = str.split(/ (?!\|)/);
console.log(arr);

......所以我们必须做得更多。可能最简单的事情是在拆分后用空格替换空格+栏:

var str = "How are you |doing today?";
var arr = str.split(/ (?!\|)/).map(function(s) {
  return s.replace(/ \|/g, ' ');
});
console.log(arr);

或在ES2015 +中:

const str = "How are you |doing today?";
const arr = str.split(/ (?!\|)/).map(s => s.replace(/ \|/g, ' '));
console.log(arr);

答案 2 :(得分:0)

首先用管道替换所有空白区域。每次遇到两个或更多管道时,请用空格替换。然后通过管道分割:

&#13;
&#13;
var str = `How  are you |doing today?
fine | thanx`;
var arr = str.replace(/ {1,}/g,"|").replace(/\|{2,}/g," ").split(/\||\n/);
console.log(arr);
&#13;
&#13;
&#13;